repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/introspect.py
|
running_service_owners
|
python
|
def running_service_owners(
exclude=('/dev', '/home', '/media', '/proc', '/run', '/sys/', '/tmp',
'/var')
):
'''
Determine which packages own the currently running services. By default,
excludes files whose full path starts with ``/dev``, ``/home``, ``/media``,
``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be
overridden by passing in a new list to ``exclude``.
CLI Example:
salt myminion introspect.running_service_owners
'''
error = {}
if 'pkg.owner' not in __salt__:
error['Unsupported Package Manager'] = (
'The module for the package manager on this system does not '
'support looking up which package(s) owns which file(s)'
)
if 'file.open_files' not in __salt__:
error['Unsupported File Module'] = (
'The file module on this system does not '
'support looking up open files on the system'
)
if error:
return {'Error': error}
ret = {}
open_files = __salt__['file.open_files']()
execs = __salt__['service.execs']()
for path in open_files:
ignore = False
for bad_dir in exclude:
if path.startswith(bad_dir):
ignore = True
if ignore:
continue
if not os.access(path, os.X_OK):
continue
for service in execs:
if path == execs[service]:
pkg = __salt__['pkg.owner'](path)
ret[service] = next(six.itervalues(pkg))
return ret
|
Determine which packages own the currently running services. By default,
excludes files whose full path starts with ``/dev``, ``/home``, ``/media``,
``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be
overridden by passing in a new list to ``exclude``.
CLI Example:
salt myminion introspect.running_service_owners
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/introspect.py#L15-L66
|
[
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to perform introspection on a minion, and return data in a format
usable by Salt States
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import 3rd-party libs
from salt.ext import six
def enabled_service_owners():
'''
Return which packages own each of the services that are currently enabled.
CLI Example:
salt myminion introspect.enabled_service_owners
'''
error = {}
if 'pkg.owner' not in __salt__:
error['Unsupported Package Manager'] = (
'The module for the package manager on this system does not '
'support looking up which package(s) owns which file(s)'
)
if 'service.show' not in __salt__:
error['Unsupported Service Manager'] = (
'The module for the service manager on this system does not '
'support showing descriptive service data'
)
if error:
return {'Error': error}
ret = {}
services = __salt__['service.get_enabled']()
for service in services:
data = __salt__['service.show'](service)
if 'ExecStart' not in data:
continue
start_cmd = data['ExecStart']['path']
pkg = __salt__['pkg.owner'](start_cmd)
ret[service] = next(six.itervalues(pkg))
return ret
def service_highstate(requires=True):
'''
Return running and enabled services in a highstate structure. By default
also returns package dependencies for those services, which means that
package definitions must be created outside this function. To drop the
package dependencies, set ``requires`` to False.
CLI Example:
salt myminion introspect.service_highstate
salt myminion introspect.service_highstate requires=False
'''
ret = {}
running = running_service_owners()
for service in running:
ret[service] = {'service': ['running']}
if requires:
ret[service]['service'].append(
{'require': {'pkg': running[service]}}
)
enabled = enabled_service_owners()
for service in enabled:
if service in ret:
ret[service]['service'].append({'enabled': True})
else:
ret[service] = {'service': [{'enabled': True}]}
if requires:
exists = False
for item in ret[service]['service']:
if isinstance(item, dict) and next(six.iterkeys(item)) == 'require':
exists = True
if not exists:
ret[service]['service'].append(
{'require': {'pkg': enabled[service]}}
)
return ret
|
saltstack/salt
|
salt/modules/introspect.py
|
enabled_service_owners
|
python
|
def enabled_service_owners():
'''
Return which packages own each of the services that are currently enabled.
CLI Example:
salt myminion introspect.enabled_service_owners
'''
error = {}
if 'pkg.owner' not in __salt__:
error['Unsupported Package Manager'] = (
'The module for the package manager on this system does not '
'support looking up which package(s) owns which file(s)'
)
if 'service.show' not in __salt__:
error['Unsupported Service Manager'] = (
'The module for the service manager on this system does not '
'support showing descriptive service data'
)
if error:
return {'Error': error}
ret = {}
services = __salt__['service.get_enabled']()
for service in services:
data = __salt__['service.show'](service)
if 'ExecStart' not in data:
continue
start_cmd = data['ExecStart']['path']
pkg = __salt__['pkg.owner'](start_cmd)
ret[service] = next(six.itervalues(pkg))
return ret
|
Return which packages own each of the services that are currently enabled.
CLI Example:
salt myminion introspect.enabled_service_owners
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/introspect.py#L69-L104
|
[
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to perform introspection on a minion, and return data in a format
usable by Salt States
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import 3rd-party libs
from salt.ext import six
def running_service_owners(
exclude=('/dev', '/home', '/media', '/proc', '/run', '/sys/', '/tmp',
'/var')
):
'''
Determine which packages own the currently running services. By default,
excludes files whose full path starts with ``/dev``, ``/home``, ``/media``,
``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be
overridden by passing in a new list to ``exclude``.
CLI Example:
salt myminion introspect.running_service_owners
'''
error = {}
if 'pkg.owner' not in __salt__:
error['Unsupported Package Manager'] = (
'The module for the package manager on this system does not '
'support looking up which package(s) owns which file(s)'
)
if 'file.open_files' not in __salt__:
error['Unsupported File Module'] = (
'The file module on this system does not '
'support looking up open files on the system'
)
if error:
return {'Error': error}
ret = {}
open_files = __salt__['file.open_files']()
execs = __salt__['service.execs']()
for path in open_files:
ignore = False
for bad_dir in exclude:
if path.startswith(bad_dir):
ignore = True
if ignore:
continue
if not os.access(path, os.X_OK):
continue
for service in execs:
if path == execs[service]:
pkg = __salt__['pkg.owner'](path)
ret[service] = next(six.itervalues(pkg))
return ret
def service_highstate(requires=True):
'''
Return running and enabled services in a highstate structure. By default
also returns package dependencies for those services, which means that
package definitions must be created outside this function. To drop the
package dependencies, set ``requires`` to False.
CLI Example:
salt myminion introspect.service_highstate
salt myminion introspect.service_highstate requires=False
'''
ret = {}
running = running_service_owners()
for service in running:
ret[service] = {'service': ['running']}
if requires:
ret[service]['service'].append(
{'require': {'pkg': running[service]}}
)
enabled = enabled_service_owners()
for service in enabled:
if service in ret:
ret[service]['service'].append({'enabled': True})
else:
ret[service] = {'service': [{'enabled': True}]}
if requires:
exists = False
for item in ret[service]['service']:
if isinstance(item, dict) and next(six.iterkeys(item)) == 'require':
exists = True
if not exists:
ret[service]['service'].append(
{'require': {'pkg': enabled[service]}}
)
return ret
|
saltstack/salt
|
salt/modules/introspect.py
|
service_highstate
|
python
|
def service_highstate(requires=True):
'''
Return running and enabled services in a highstate structure. By default
also returns package dependencies for those services, which means that
package definitions must be created outside this function. To drop the
package dependencies, set ``requires`` to False.
CLI Example:
salt myminion introspect.service_highstate
salt myminion introspect.service_highstate requires=False
'''
ret = {}
running = running_service_owners()
for service in running:
ret[service] = {'service': ['running']}
if requires:
ret[service]['service'].append(
{'require': {'pkg': running[service]}}
)
enabled = enabled_service_owners()
for service in enabled:
if service in ret:
ret[service]['service'].append({'enabled': True})
else:
ret[service] = {'service': [{'enabled': True}]}
if requires:
exists = False
for item in ret[service]['service']:
if isinstance(item, dict) and next(six.iterkeys(item)) == 'require':
exists = True
if not exists:
ret[service]['service'].append(
{'require': {'pkg': enabled[service]}}
)
return ret
|
Return running and enabled services in a highstate structure. By default
also returns package dependencies for those services, which means that
package definitions must be created outside this function. To drop the
package dependencies, set ``requires`` to False.
CLI Example:
salt myminion introspect.service_highstate
salt myminion introspect.service_highstate requires=False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/introspect.py#L107-L146
|
[
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def running_service_owners(\n exclude=('/dev', '/home', '/media', '/proc', '/run', '/sys/', '/tmp',\n '/var')\n ):\n '''\n Determine which packages own the currently running services. By default,\n excludes files whose full path starts with ``/dev``, ``/home``, ``/media``,\n ``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be\n overridden by passing in a new list to ``exclude``.\n\n CLI Example:\n\n salt myminion introspect.running_service_owners\n '''\n error = {}\n if 'pkg.owner' not in __salt__:\n error['Unsupported Package Manager'] = (\n 'The module for the package manager on this system does not '\n 'support looking up which package(s) owns which file(s)'\n )\n\n if 'file.open_files' not in __salt__:\n error['Unsupported File Module'] = (\n 'The file module on this system does not '\n 'support looking up open files on the system'\n )\n\n if error:\n return {'Error': error}\n\n ret = {}\n open_files = __salt__['file.open_files']()\n\n execs = __salt__['service.execs']()\n for path in open_files:\n ignore = False\n for bad_dir in exclude:\n if path.startswith(bad_dir):\n ignore = True\n\n if ignore:\n continue\n\n if not os.access(path, os.X_OK):\n continue\n\n for service in execs:\n if path == execs[service]:\n pkg = __salt__['pkg.owner'](path)\n ret[service] = next(six.itervalues(pkg))\n\n return ret\n",
"def enabled_service_owners():\n '''\n Return which packages own each of the services that are currently enabled.\n\n CLI Example:\n\n salt myminion introspect.enabled_service_owners\n '''\n error = {}\n if 'pkg.owner' not in __salt__:\n error['Unsupported Package Manager'] = (\n 'The module for the package manager on this system does not '\n 'support looking up which package(s) owns which file(s)'\n )\n\n if 'service.show' not in __salt__:\n error['Unsupported Service Manager'] = (\n 'The module for the service manager on this system does not '\n 'support showing descriptive service data'\n )\n\n if error:\n return {'Error': error}\n\n ret = {}\n services = __salt__['service.get_enabled']()\n\n for service in services:\n data = __salt__['service.show'](service)\n if 'ExecStart' not in data:\n continue\n start_cmd = data['ExecStart']['path']\n pkg = __salt__['pkg.owner'](start_cmd)\n ret[service] = next(six.itervalues(pkg))\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Functions to perform introspection on a minion, and return data in a format
usable by Salt States
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import 3rd-party libs
from salt.ext import six
def running_service_owners(
exclude=('/dev', '/home', '/media', '/proc', '/run', '/sys/', '/tmp',
'/var')
):
'''
Determine which packages own the currently running services. By default,
excludes files whose full path starts with ``/dev``, ``/home``, ``/media``,
``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be
overridden by passing in a new list to ``exclude``.
CLI Example:
salt myminion introspect.running_service_owners
'''
error = {}
if 'pkg.owner' not in __salt__:
error['Unsupported Package Manager'] = (
'The module for the package manager on this system does not '
'support looking up which package(s) owns which file(s)'
)
if 'file.open_files' not in __salt__:
error['Unsupported File Module'] = (
'The file module on this system does not '
'support looking up open files on the system'
)
if error:
return {'Error': error}
ret = {}
open_files = __salt__['file.open_files']()
execs = __salt__['service.execs']()
for path in open_files:
ignore = False
for bad_dir in exclude:
if path.startswith(bad_dir):
ignore = True
if ignore:
continue
if not os.access(path, os.X_OK):
continue
for service in execs:
if path == execs[service]:
pkg = __salt__['pkg.owner'](path)
ret[service] = next(six.itervalues(pkg))
return ret
def enabled_service_owners():
'''
Return which packages own each of the services that are currently enabled.
CLI Example:
salt myminion introspect.enabled_service_owners
'''
error = {}
if 'pkg.owner' not in __salt__:
error['Unsupported Package Manager'] = (
'The module for the package manager on this system does not '
'support looking up which package(s) owns which file(s)'
)
if 'service.show' not in __salt__:
error['Unsupported Service Manager'] = (
'The module for the service manager on this system does not '
'support showing descriptive service data'
)
if error:
return {'Error': error}
ret = {}
services = __salt__['service.get_enabled']()
for service in services:
data = __salt__['service.show'](service)
if 'ExecStart' not in data:
continue
start_cmd = data['ExecStart']['path']
pkg = __salt__['pkg.owner'](start_cmd)
ret[service] = next(six.itervalues(pkg))
return ret
|
saltstack/salt
|
salt/roster/clustershell.py
|
targets
|
python
|
def targets(tgt, tgt_type='glob', **kwargs):
'''
Return the targets
'''
ret = {}
ports = __opts__['ssh_scan_ports']
if not isinstance(ports, list):
# Comma-separate list of integers
ports = list(map(int, six.text_type(ports).split(',')))
hosts = list(NodeSet(tgt))
host_addrs = dict([(h, socket.gethostbyname(h)) for h in hosts])
for host, addr in host_addrs.items():
addr = six.text_type(addr)
ret[host] = copy.deepcopy(__opts__.get('roster_defaults', {}))
for port in ports:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(float(__opts__['ssh_scan_timeout']))
sock.connect((addr, port))
sock.shutdown(socket.SHUT_RDWR)
sock.close()
ret[host].update({'host': addr, 'port': port})
except socket.error:
pass
return ret
|
Return the targets
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/clustershell.py#L33-L59
| null |
# -*- coding: utf-8 -*-
'''
This roster resolves hostname in a pdsh/clustershell style.
:depends: clustershell, https://github.com/cea-hpc/clustershell
When you want to use host globs for target matching, use ``--roster clustershell``. For example:
.. code-block:: bash
salt-ssh --roster clustershell 'server_[1-10,21-30],test_server[5,7,9]' test.ping
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import socket
import copy
from salt.ext import six
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REQ_ERROR = None
try:
from ClusterShell.NodeSet import NodeSet
except (ImportError, OSError) as e:
REQ_ERROR = 'ClusterShell import error, perhaps missing python ClusterShell package'
def __virtual__():
return (REQ_ERROR is None, REQ_ERROR)
|
saltstack/salt
|
salt/config/__init__.py
|
_gather_buffer_space
|
python
|
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
|
Gather some system data and then calculate
buffer space.
Result is in bytes.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L76-L95
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_normalize_roots
|
python
|
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
|
Normalize file or pillar roots.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L1956-L1968
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_validate_pillar_roots
|
python
|
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
|
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L1971-L1980
|
[
"def _expand_glob_path(file_roots):\n '''\n Applies shell globbing to a set of directories and returns\n the expanded paths\n '''\n unglobbed_path = []\n for path in file_roots:\n try:\n if glob.has_magic(path):\n unglobbed_path.extend(glob.glob(path))\n else:\n unglobbed_path.append(path)\n except Exception:\n unglobbed_path.append(path)\n return unglobbed_path\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_validate_file_roots
|
python
|
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
|
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L1983-L1992
|
[
"def _expand_glob_path(file_roots):\n '''\n Applies shell globbing to a set of directories and returns\n the expanded paths\n '''\n unglobbed_path = []\n for path in file_roots:\n try:\n if glob.has_magic(path):\n unglobbed_path.extend(glob.glob(path))\n else:\n unglobbed_path.append(path)\n except Exception:\n unglobbed_path.append(path)\n return unglobbed_path\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_expand_glob_path
|
python
|
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
|
Applies shell globbing to a set of directories and returns
the expanded paths
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L1995-L2009
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_validate_opts
|
python
|
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
|
Check that all of the types of values passed into the config are
of the right types
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2012-L2112
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def format_multi_opt(valid_type):\n try:\n num_types = len(valid_type)\n except TypeError:\n # Bare type name won't have a length, return the name of the type\n # passed.\n return valid_type.__name__\n else:\n def get_types(types, type_tuple):\n for item in type_tuple:\n if isinstance(item, tuple):\n get_types(types, item)\n else:\n try:\n types.append(item.__name__)\n except AttributeError:\n log.warning(\n 'Unable to interpret type %s while validating '\n 'configuration', item\n )\n types = []\n get_types(types, valid_type)\n\n ret = ', '.join(types[:-1])\n ret += ' or ' + types[-1]\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_validate_ssh_minion_opts
|
python
|
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
|
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2115-L2135
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_append_domain
|
python
|
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
|
Append a domain to the existing id if it doesn't already exist
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2138-L2148
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_read_conf_file
|
python
|
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
|
Read in a config file from a given path and process it into a dictionary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2151-L2178
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_absolute_path
|
python
|
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
|
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2181-L2198
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
load_config
|
python
|
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
|
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2201-L2261
|
[
"def _read_conf_file(path):\n '''\n Read in a config file from a given path and process it into a dictionary\n '''\n log.debug('Reading configuration from %s', path)\n with salt.utils.files.fopen(path, 'r') as conf_file:\n try:\n conf_opts = salt.utils.yaml.safe_load(conf_file) or {}\n except salt.utils.yaml.YAMLError as err:\n message = 'Error parsing configuration file: {0} - {1}'.format(path, err)\n log.error(message)\n raise salt.exceptions.SaltConfigurationError(message)\n\n # only interpret documents as a valid conf, not things like strings,\n # which might have been caused by invalid yaml syntax\n if not isinstance(conf_opts, dict):\n message = 'Error parsing configuration file: {0} - conf ' \\\n 'should be a document, not {1}.'.format(path, type(conf_opts))\n log.error(message)\n raise salt.exceptions.SaltConfigurationError(message)\n\n # allow using numeric ids: convert int to string\n if 'id' in conf_opts:\n if not isinstance(conf_opts['id'], six.string_types):\n conf_opts['id'] = six.text_type(conf_opts['id'])\n else:\n conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])\n return conf_opts\n",
"def is_readable(path):\n '''\n Check if a given path is readable by the current user.\n\n :param path: The path to check\n :returns: True or False\n '''\n\n if os.access(path, os.F_OK) and os.access(path, os.R_OK):\n # The path exists and is readable\n return True\n\n # The path does not exist\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
include_config
|
python
|
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
|
Parses extra configuration file(s) specified in an include list in the
main config file.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2264-L2318
|
[
"def update(dest, upd, recursive_update=True, merge_lists=False):\n '''\n Recursive version of the default dict.update\n\n Merges upd recursively into dest\n\n If recursive_update=False, will use the classic dict.update, or fall back\n on a manual merge (helpful for non-dict types like FunctionWrapper)\n\n If merge_lists=True, will aggregate list object types instead of replace.\n The list in ``upd`` is added to the list in ``dest``, so the resulting list\n is ``dest[key] + upd[key]``. This behavior is only activated when\n recursive_update=True. By default merge_lists=False.\n\n .. versionchanged: 2016.11.6\n When merging lists, duplicate values are removed. Values already\n present in the ``dest`` list are not added from the ``upd`` list.\n '''\n if (not isinstance(dest, Mapping)) \\\n or (not isinstance(upd, Mapping)):\n raise TypeError('Cannot update using non-dict types in dictupdate.update()')\n updkeys = list(upd.keys())\n if not set(list(dest.keys())) & set(updkeys):\n recursive_update = False\n if recursive_update:\n for key in updkeys:\n val = upd[key]\n try:\n dest_subkey = dest.get(key, None)\n except AttributeError:\n dest_subkey = None\n if isinstance(dest_subkey, Mapping) \\\n and isinstance(val, Mapping):\n ret = update(dest_subkey, val, merge_lists=merge_lists)\n dest[key] = ret\n elif isinstance(dest_subkey, list) and isinstance(val, list):\n if merge_lists:\n merged = copy.deepcopy(dest_subkey)\n merged.extend([x for x in val if x not in merged])\n dest[key] = merged\n else:\n dest[key] = upd[key]\n else:\n dest[key] = upd[key]\n return dest\n try:\n for k in upd:\n dest[k] = upd[k]\n except AttributeError:\n # this mapping is not a dict\n for k in upd:\n dest[k] = upd[k]\n return dest\n",
"def include_config(include, orig_path, verbose, exit_on_config_errors=False):\n '''\n Parses extra configuration file(s) specified in an include list in the\n main config file.\n '''\n # Protect against empty option\n if not include:\n return {}\n\n if orig_path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if isinstance(include, six.string_types):\n include = [include]\n\n configuration = {}\n for path in include:\n # Allow for includes like ~/foo\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n path = os.path.join(os.path.dirname(orig_path), path)\n\n # Catch situation where user typos path in configuration; also warns\n # for empty include directory (which might be by design)\n glob_matches = glob.glob(path)\n if not glob_matches:\n if verbose:\n log.warning(\n 'Warning parsing configuration file: \"include\" path/glob '\n \"'%s' matches no files\", path\n )\n\n for fn_ in sorted(glob_matches):\n log.debug('Including configuration from \\'%s\\'', fn_)\n try:\n opts = _read_conf_file(fn_)\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n # Initialize default config if we wish to skip config errors\n opts = {}\n schedule = opts.get('schedule', {})\n if schedule and 'schedule' in configuration:\n configuration['schedule'].update(schedule)\n include = opts.get('include', [])\n if include:\n opts.update(include_config(include, fn_, verbose))\n\n salt.utils.dictupdate.update(configuration, opts, True, True)\n\n return configuration\n",
"def _read_conf_file(path):\n '''\n Read in a config file from a given path and process it into a dictionary\n '''\n log.debug('Reading configuration from %s', path)\n with salt.utils.files.fopen(path, 'r') as conf_file:\n try:\n conf_opts = salt.utils.yaml.safe_load(conf_file) or {}\n except salt.utils.yaml.YAMLError as err:\n message = 'Error parsing configuration file: {0} - {1}'.format(path, err)\n log.error(message)\n raise salt.exceptions.SaltConfigurationError(message)\n\n # only interpret documents as a valid conf, not things like strings,\n # which might have been caused by invalid yaml syntax\n if not isinstance(conf_opts, dict):\n message = 'Error parsing configuration file: {0} - conf ' \\\n 'should be a document, not {1}.'.format(path, type(conf_opts))\n log.error(message)\n raise salt.exceptions.SaltConfigurationError(message)\n\n # allow using numeric ids: convert int to string\n if 'id' in conf_opts:\n if not isinstance(conf_opts['id'], six.string_types):\n conf_opts['id'] = six.text_type(conf_opts['id'])\n else:\n conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])\n return conf_opts\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
prepend_root_dir
|
python
|
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
|
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2321-L2367
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
insert_system_path
|
python
|
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
|
Inserts path into python path taking into consideration 'root_dir' option.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2370-L2381
|
[
"def prepend_root_dir(opts, path_options):\n '''\n Prepends the options that represent filesystem paths with value of the\n 'root_dir' option.\n '''\n root_dir = os.path.abspath(opts['root_dir'])\n def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)\n for path_option in path_options:\n if path_option in opts:\n path = opts[path_option]\n tmp_path_def_root_dir = None\n tmp_path_root_dir = None\n # When running testsuite, salt.syspaths.ROOT_DIR is often empty\n if path == def_root_dir or path.startswith(def_root_dir + os.sep):\n # Remove the default root dir prefix\n tmp_path_def_root_dir = path[len(def_root_dir):]\n if root_dir and (path == root_dir or\n path.startswith(root_dir + os.sep)):\n # Remove the root dir prefix\n tmp_path_root_dir = path[len(root_dir):]\n if tmp_path_def_root_dir and not tmp_path_root_dir:\n # Just the default root dir matched\n path = tmp_path_def_root_dir\n elif tmp_path_root_dir and not tmp_path_def_root_dir:\n # Just the root dir matched\n path = tmp_path_root_dir\n elif tmp_path_def_root_dir and tmp_path_root_dir:\n # In this case both the default root dir and the override root\n # dir matched; this means that either\n # def_root_dir is a substring of root_dir or vice versa\n # We must choose the most specific path\n if def_root_dir in root_dir:\n path = tmp_path_root_dir\n else:\n path = tmp_path_def_root_dir\n elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:\n # In windows, os.path.isabs resolves '/' to 'C:\\\\' or whatever\n # the root drive is. This elif prevents the next from being\n # hit, so that the root_dir is prefixed in cases where the\n # drive is not prefixed on a config option\n pass\n elif os.path.isabs(path):\n # Absolute path (not default or overridden root_dir)\n # No prepending required\n continue\n # Prepending the root dir\n opts[path_option] = salt.utils.path.join(root_dir, path)\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
minion_config
|
python
|
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
|
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2384-L2433
|
[
"def include_config(include, orig_path, verbose, exit_on_config_errors=False):\n '''\n Parses extra configuration file(s) specified in an include list in the\n main config file.\n '''\n # Protect against empty option\n if not include:\n return {}\n\n if orig_path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if isinstance(include, six.string_types):\n include = [include]\n\n configuration = {}\n for path in include:\n # Allow for includes like ~/foo\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n path = os.path.join(os.path.dirname(orig_path), path)\n\n # Catch situation where user typos path in configuration; also warns\n # for empty include directory (which might be by design)\n glob_matches = glob.glob(path)\n if not glob_matches:\n if verbose:\n log.warning(\n 'Warning parsing configuration file: \"include\" path/glob '\n \"'%s' matches no files\", path\n )\n\n for fn_ in sorted(glob_matches):\n log.debug('Including configuration from \\'%s\\'', fn_)\n try:\n opts = _read_conf_file(fn_)\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n # Initialize default config if we wish to skip config errors\n opts = {}\n schedule = opts.get('schedule', {})\n if schedule and 'schedule' in configuration:\n configuration['schedule'].update(schedule)\n include = opts.get('include', [])\n if include:\n opts.update(include_config(include, fn_, verbose))\n\n salt.utils.dictupdate.update(configuration, opts, True, True)\n\n return configuration\n",
"def _validate_opts(opts):\n '''\n Check that all of the types of values passed into the config are\n of the right types\n '''\n def format_multi_opt(valid_type):\n try:\n num_types = len(valid_type)\n except TypeError:\n # Bare type name won't have a length, return the name of the type\n # passed.\n return valid_type.__name__\n else:\n def get_types(types, type_tuple):\n for item in type_tuple:\n if isinstance(item, tuple):\n get_types(types, item)\n else:\n try:\n types.append(item.__name__)\n except AttributeError:\n log.warning(\n 'Unable to interpret type %s while validating '\n 'configuration', item\n )\n types = []\n get_types(types, valid_type)\n\n ret = ', '.join(types[:-1])\n ret += ' or ' + types[-1]\n return ret\n\n errors = []\n\n err = (\n 'Config option \\'{0}\\' with value {1} has an invalid type of {2}, a '\n '{3} is required for this option'\n )\n for key, val in six.iteritems(opts):\n if key in VALID_OPTS:\n if val is None:\n if VALID_OPTS[key] is None:\n continue\n else:\n try:\n if None in VALID_OPTS[key]:\n continue\n except TypeError:\n # VALID_OPTS[key] is not iterable and not None\n pass\n\n if isinstance(val, VALID_OPTS[key]):\n continue\n\n # We don't know what data type sdb will return at run-time so we\n # simply cannot check it for correctness here at start-time.\n if isinstance(val, six.string_types) and val.startswith('sdb://'):\n continue\n\n if hasattr(VALID_OPTS[key], '__call__'):\n try:\n VALID_OPTS[key](val)\n if isinstance(val, (list, dict)):\n # We'll only get here if VALID_OPTS[key] is str or\n # bool, and the passed value is a list/dict. Attempting\n # to run int() or float() on a list/dict will raise an\n # exception, but running str() or bool() on it will\n # pass despite not being the correct type.\n errors.append(\n err.format(\n key,\n val,\n type(val).__name__,\n VALID_OPTS[key].__name__\n )\n )\n except (TypeError, ValueError):\n errors.append(\n err.format(key,\n val,\n type(val).__name__,\n VALID_OPTS[key].__name__)\n )\n continue\n\n errors.append(\n err.format(key,\n val,\n type(val).__name__,\n format_multi_opt(VALID_OPTS[key]))\n )\n\n # Convert list to comma-delimited string for 'return' config option\n if isinstance(opts.get('return'), list):\n opts['return'] = ','.join(opts['return'])\n\n for error in errors:\n log.warning(error)\n if errors:\n return False\n return True\n",
"def load_config(path, env_var, default_path=None, exit_on_config_errors=True):\n '''\n Returns configuration dict from parsing either the file described by\n ``path`` or the environment variable described by ``env_var`` as YAML.\n '''\n if path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if default_path is None:\n # This is most likely not being used from salt, i.e., could be salt-cloud\n # or salt-api which have not yet migrated to the new default_path\n # argument. Let's issue a warning message that the environ vars won't\n # work.\n import inspect\n previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)\n log.warning(\n \"The function '%s()' defined in '%s' is not yet using the \"\n \"new 'default_path' argument to `salt.config.load_config()`. \"\n \"As such, the '%s' environment variable will be ignored\",\n previous_frame.function, previous_frame.filename, env_var\n )\n # In this case, maintain old behavior\n default_path = DEFAULT_MASTER_OPTS['conf_file']\n\n # Default to the environment variable path, if it exists\n env_path = os.environ.get(env_var, path)\n if not env_path or not os.path.isfile(env_path):\n env_path = path\n # If non-default path from `-c`, use that over the env variable\n if path != default_path:\n env_path = path\n\n path = env_path\n\n # If the configuration file is missing, attempt to copy the template,\n # after removing the first header line.\n if not os.path.isfile(path):\n template = '{0}.template'.format(path)\n if os.path.isfile(template):\n log.debug('Writing %s based on %s', path, template)\n with salt.utils.files.fopen(path, 'w') as out:\n with salt.utils.files.fopen(template, 'r') as ifile:\n ifile.readline() # skip first line\n out.write(ifile.read())\n\n opts = {}\n\n if salt.utils.validate.path.is_readable(path):\n try:\n opts = _read_conf_file(path)\n opts['conf_file'] = path\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n log.debug('Missing configuration file: %s', path)\n\n return opts\n",
"def apply_minion_config(overrides=None,\n defaults=None,\n cache_minion_id=False,\n minion_id=None):\n '''\n Returns minion configurations dict.\n '''\n if defaults is None:\n defaults = DEFAULT_MINION_OPTS.copy()\n if overrides is None:\n overrides = {}\n\n opts = defaults.copy()\n opts['__role'] = 'minion'\n _adjust_log_file_override(overrides, defaults['log_file'])\n if overrides:\n opts.update(overrides)\n\n if 'environment' in opts:\n if opts['saltenv'] is not None:\n log.warning(\n 'The \\'saltenv\\' and \\'environment\\' minion config options '\n 'cannot both be used. Ignoring \\'environment\\' in favor of '\n '\\'saltenv\\'.',\n )\n # Set environment to saltenv in case someone's custom module is\n # refrencing __opts__['environment']\n opts['environment'] = opts['saltenv']\n else:\n log.warning(\n 'The \\'environment\\' minion config option has been renamed '\n 'to \\'saltenv\\'. Using %s as the \\'saltenv\\' config value.',\n opts['environment']\n )\n opts['saltenv'] = opts['environment']\n\n for idx, val in enumerate(opts['fileserver_backend']):\n if val in ('git', 'hg', 'svn', 'minion'):\n new_val = val + 'fs'\n log.debug(\n 'Changed %s to %s in minion opts\\' fileserver_backend list',\n val, new_val\n )\n opts['fileserver_backend'][idx] = new_val\n\n opts['__cli'] = salt.utils.stringutils.to_unicode(\n os.path.basename(sys.argv[0])\n )\n\n # No ID provided. Will getfqdn save us?\n using_ip_for_id = False\n if not opts.get('id'):\n if minion_id:\n opts['id'] = minion_id\n else:\n opts['id'], using_ip_for_id = get_id(\n opts,\n cache_minion_id=cache_minion_id)\n\n # it does not make sense to append a domain to an IP based id\n if not using_ip_for_id and 'append_domain' in opts:\n opts['id'] = _append_domain(opts)\n\n for directory in opts.get('append_minionid_config_dirs', []):\n if directory in ('pki_dir', 'cachedir', 'extension_modules'):\n newdirectory = os.path.join(opts[directory], opts['id'])\n opts[directory] = newdirectory\n elif directory == 'default_include' and directory in opts:\n include_dir = os.path.dirname(opts[directory])\n new_include_dir = os.path.join(include_dir,\n opts['id'],\n os.path.basename(opts[directory]))\n opts[directory] = new_include_dir\n\n # pidfile can be in the list of append_minionid_config_dirs, but pidfile\n # is the actual path with the filename, not a directory.\n if 'pidfile' in opts.get('append_minionid_config_dirs', []):\n newpath_list = os.path.split(opts['pidfile'])\n opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])\n\n if len(opts['sock_dir']) > len(opts['cachedir']) + 10:\n opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')\n\n # Enabling open mode requires that the value be set to True, and\n # nothing else!\n opts['open_mode'] = opts['open_mode'] is True\n opts['file_roots'] = _validate_file_roots(opts['file_roots'])\n opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])\n # Make sure ext_mods gets set if it is an untrue value\n # (here to catch older bad configs)\n opts['extension_modules'] = (\n opts.get('extension_modules') or\n os.path.join(opts['cachedir'], 'extmods')\n )\n # Set up the utils_dirs location from the extension_modules location\n opts['utils_dirs'] = (\n opts.get('utils_dirs') or\n [os.path.join(opts['extension_modules'], 'utils')]\n )\n\n # Insert all 'utils_dirs' directories to the system path\n insert_system_path(opts, opts['utils_dirs'])\n\n # Prepend root_dir to other paths\n prepend_root_dirs = [\n 'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',\n ]\n\n # These can be set to syslog, so, not actual paths on the system\n for config_key in ('log_file', 'key_logfile'):\n if urlparse(opts.get(config_key, '')).scheme == '':\n prepend_root_dirs.append(config_key)\n\n prepend_root_dir(opts, prepend_root_dirs)\n\n # if there is no beacons option yet, add an empty beacons dict\n if 'beacons' not in opts:\n opts['beacons'] = {}\n\n if overrides.get('ipc_write_buffer', '') == 'dynamic':\n opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER\n\n # Make sure hash_type is lowercase\n opts['hash_type'] = opts['hash_type'].lower()\n\n # Check and update TLS/SSL configuration\n _update_ssl_config(opts)\n _update_discovery_config(opts)\n\n return opts\n",
"def apply_sdb(opts, sdb_opts=None):\n '''\n Recurse for sdb:// links for opts\n '''\n # Late load of SDB to keep CLI light\n import salt.utils.sdb\n if sdb_opts is None:\n sdb_opts = opts\n if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):\n return salt.utils.sdb.sdb_get(sdb_opts, opts)\n elif isinstance(sdb_opts, dict):\n for key, value in six.iteritems(sdb_opts):\n if value is None:\n continue\n sdb_opts[key] = apply_sdb(opts, value)\n elif isinstance(sdb_opts, list):\n for key, value in enumerate(sdb_opts):\n if value is None:\n continue\n sdb_opts[key] = apply_sdb(opts, value)\n\n return sdb_opts\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
apply_sdb
|
python
|
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
|
Recurse for sdb:// links for opts
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2560-L2581
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def apply_sdb(opts, sdb_opts=None):\n '''\n Recurse for sdb:// links for opts\n '''\n # Late load of SDB to keep CLI light\n import salt.utils.sdb\n if sdb_opts is None:\n sdb_opts = opts\n if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):\n return salt.utils.sdb.sdb_get(sdb_opts, opts)\n elif isinstance(sdb_opts, dict):\n for key, value in six.iteritems(sdb_opts):\n if value is None:\n continue\n sdb_opts[key] = apply_sdb(opts, value)\n elif isinstance(sdb_opts, list):\n for key, value in enumerate(sdb_opts):\n if value is None:\n continue\n sdb_opts[key] = apply_sdb(opts, value)\n\n return sdb_opts\n",
"def sdb_get(uri, opts, utils=None):\n '''\n Get a value from a db, using a uri in the form of ``sdb://<profile>/<key>``. If\n the uri provided does not start with ``sdb://``, then it will be returned as-is.\n '''\n if not isinstance(uri, string_types) or not uri.startswith('sdb://'):\n return uri\n\n if utils is None:\n utils = salt.loader.utils(opts)\n\n sdlen = len('sdb://')\n indx = uri.find('/', sdlen)\n\n if (indx == -1) or not uri[(indx + 1):]:\n return uri\n\n profile = opts.get(uri[sdlen:indx], {})\n if not profile:\n profile = opts.get('pillar', {}).get(uri[sdlen:indx], {})\n if 'driver' not in profile:\n return uri\n\n fun = '{0}.get'.format(profile['driver'])\n query = uri[indx+1:]\n\n loaded_db = salt.loader.sdb(opts, fun, utils=utils)\n return loaded_db[fun](query, profile=profile)\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
cloud_config
|
python
|
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
|
Read in the Salt Cloud config and return the dict
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2585-L2810
|
[
"def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):\n '''\n Reads in the master configuration file and sets up default options\n\n This is useful for running the actual master daemon. For running\n Master-side client interfaces that need the master opts see\n :py:func:`salt.client.client_config`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n if not os.environ.get(env_var, None):\n # No valid setting was given using the configuration variable.\n # Lets see is SALT_CONFIG_DIR is of any use\n salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)\n if salt_config_dir:\n env_config_file_path = os.path.join(salt_config_dir, 'master')\n if salt_config_dir and os.path.isfile(env_config_file_path):\n # We can get a configuration file using SALT_CONFIG_DIR, let's\n # update the environment with this information\n os.environ[env_var] = env_config_file_path\n\n overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])\n default_include = overrides.get('default_include',\n defaults['default_include'])\n include = overrides.get('include', [])\n\n overrides.update(include_config(default_include, path, verbose=False,\n exit_on_config_errors=exit_on_config_errors))\n overrides.update(include_config(include, path, verbose=True,\n exit_on_config_errors=exit_on_config_errors))\n opts = apply_master_config(overrides, defaults)\n _validate_ssh_minion_opts(opts)\n _validate_opts(opts)\n # If 'nodegroups:' is uncommented in the master config file, and there are\n # no nodegroups defined, opts['nodegroups'] will be None. Fix this by\n # reverting this value to the default, as if 'nodegroups:' was commented\n # out or not present.\n if opts.get('nodegroups') is None:\n opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})\n if salt.utils.data.is_dictlist(opts['nodegroups']):\n opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])\n apply_sdb(opts)\n return opts\n",
"def include_config(include, orig_path, verbose, exit_on_config_errors=False):\n '''\n Parses extra configuration file(s) specified in an include list in the\n main config file.\n '''\n # Protect against empty option\n if not include:\n return {}\n\n if orig_path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if isinstance(include, six.string_types):\n include = [include]\n\n configuration = {}\n for path in include:\n # Allow for includes like ~/foo\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n path = os.path.join(os.path.dirname(orig_path), path)\n\n # Catch situation where user typos path in configuration; also warns\n # for empty include directory (which might be by design)\n glob_matches = glob.glob(path)\n if not glob_matches:\n if verbose:\n log.warning(\n 'Warning parsing configuration file: \"include\" path/glob '\n \"'%s' matches no files\", path\n )\n\n for fn_ in sorted(glob_matches):\n log.debug('Including configuration from \\'%s\\'', fn_)\n try:\n opts = _read_conf_file(fn_)\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n # Initialize default config if we wish to skip config errors\n opts = {}\n schedule = opts.get('schedule', {})\n if schedule and 'schedule' in configuration:\n configuration['schedule'].update(schedule)\n include = opts.get('include', [])\n if include:\n opts.update(include_config(include, fn_, verbose))\n\n salt.utils.dictupdate.update(configuration, opts, True, True)\n\n return configuration\n",
"def _absolute_path(path, relative_to=None):\n '''\n Return an absolute path. In case ``relative_to`` is passed and ``path`` is\n not an absolute path, we try to prepend ``relative_to`` to ``path``and if\n that path exists, return that one\n '''\n\n if path and os.path.isabs(path):\n return path\n if path and relative_to is not None:\n _abspath = os.path.join(relative_to, path)\n if os.path.isfile(_abspath):\n log.debug(\n 'Relative path \\'%s\\' converted to existing absolute path '\n '\\'%s\\'', path, _abspath\n )\n return _abspath\n return path\n",
"def load_config(path, env_var, default_path=None, exit_on_config_errors=True):\n '''\n Returns configuration dict from parsing either the file described by\n ``path`` or the environment variable described by ``env_var`` as YAML.\n '''\n if path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if default_path is None:\n # This is most likely not being used from salt, i.e., could be salt-cloud\n # or salt-api which have not yet migrated to the new default_path\n # argument. Let's issue a warning message that the environ vars won't\n # work.\n import inspect\n previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)\n log.warning(\n \"The function '%s()' defined in '%s' is not yet using the \"\n \"new 'default_path' argument to `salt.config.load_config()`. \"\n \"As such, the '%s' environment variable will be ignored\",\n previous_frame.function, previous_frame.filename, env_var\n )\n # In this case, maintain old behavior\n default_path = DEFAULT_MASTER_OPTS['conf_file']\n\n # Default to the environment variable path, if it exists\n env_path = os.environ.get(env_var, path)\n if not env_path or not os.path.isfile(env_path):\n env_path = path\n # If non-default path from `-c`, use that over the env variable\n if path != default_path:\n env_path = path\n\n path = env_path\n\n # If the configuration file is missing, attempt to copy the template,\n # after removing the first header line.\n if not os.path.isfile(path):\n template = '{0}.template'.format(path)\n if os.path.isfile(template):\n log.debug('Writing %s based on %s', path, template)\n with salt.utils.files.fopen(path, 'w') as out:\n with salt.utils.files.fopen(template, 'r') as ifile:\n ifile.readline() # skip first line\n out.write(ifile.read())\n\n opts = {}\n\n if salt.utils.validate.path.is_readable(path):\n try:\n opts = _read_conf_file(path)\n opts['conf_file'] = path\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n log.debug('Missing configuration file: %s', path)\n\n return opts\n",
"def prepend_root_dir(opts, path_options):\n '''\n Prepends the options that represent filesystem paths with value of the\n 'root_dir' option.\n '''\n root_dir = os.path.abspath(opts['root_dir'])\n def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)\n for path_option in path_options:\n if path_option in opts:\n path = opts[path_option]\n tmp_path_def_root_dir = None\n tmp_path_root_dir = None\n # When running testsuite, salt.syspaths.ROOT_DIR is often empty\n if path == def_root_dir or path.startswith(def_root_dir + os.sep):\n # Remove the default root dir prefix\n tmp_path_def_root_dir = path[len(def_root_dir):]\n if root_dir and (path == root_dir or\n path.startswith(root_dir + os.sep)):\n # Remove the root dir prefix\n tmp_path_root_dir = path[len(root_dir):]\n if tmp_path_def_root_dir and not tmp_path_root_dir:\n # Just the default root dir matched\n path = tmp_path_def_root_dir\n elif tmp_path_root_dir and not tmp_path_def_root_dir:\n # Just the root dir matched\n path = tmp_path_root_dir\n elif tmp_path_def_root_dir and tmp_path_root_dir:\n # In this case both the default root dir and the override root\n # dir matched; this means that either\n # def_root_dir is a substring of root_dir or vice versa\n # We must choose the most specific path\n if def_root_dir in root_dir:\n path = tmp_path_root_dir\n else:\n path = tmp_path_def_root_dir\n elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:\n # In windows, os.path.isabs resolves '/' to 'C:\\\\' or whatever\n # the root drive is. This elif prevents the next from being\n # hit, so that the root_dir is prefixed in cases where the\n # drive is not prefixed on a config option\n pass\n elif os.path.isabs(path):\n # Absolute path (not default or overridden root_dir)\n # No prepending required\n continue\n # Prepending the root dir\n opts[path_option] = salt.utils.path.join(root_dir, path)\n",
"def apply_sdb(opts, sdb_opts=None):\n '''\n Recurse for sdb:// links for opts\n '''\n # Late load of SDB to keep CLI light\n import salt.utils.sdb\n if sdb_opts is None:\n sdb_opts = opts\n if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):\n return salt.utils.sdb.sdb_get(sdb_opts, opts)\n elif isinstance(sdb_opts, dict):\n for key, value in six.iteritems(sdb_opts):\n if value is None:\n continue\n sdb_opts[key] = apply_sdb(opts, value)\n elif isinstance(sdb_opts, list):\n for key, value in enumerate(sdb_opts):\n if value is None:\n continue\n sdb_opts[key] = apply_sdb(opts, value)\n\n return sdb_opts\n",
"def apply_cloud_config(overrides, defaults=None):\n '''\n Return a cloud config\n '''\n if defaults is None:\n defaults = DEFAULT_CLOUD_OPTS.copy()\n\n config = defaults.copy()\n if overrides:\n config.update(overrides)\n\n # If the user defined providers in salt cloud's main configuration file, we\n # need to take care for proper and expected format.\n if 'providers' in config:\n # Keep a copy of the defined providers\n providers = config['providers'].copy()\n # Reset the providers dictionary\n config['providers'] = {}\n # Populate the providers dictionary\n for alias, details in six.iteritems(providers):\n if isinstance(details, list):\n for detail in details:\n if 'driver' not in detail:\n raise salt.exceptions.SaltCloudConfigError(\n 'The cloud provider alias \\'{0}\\' has an entry '\n 'missing the required setting of \\'driver\\'.'.format(\n alias\n )\n )\n\n driver = detail['driver']\n\n if ':' in driver:\n # Weird, but...\n alias, driver = driver.split(':')\n\n if alias not in config['providers']:\n config['providers'][alias] = {}\n\n detail['provider'] = '{0}:{1}'.format(alias, driver)\n config['providers'][alias][driver] = detail\n elif isinstance(details, dict):\n if 'driver' not in details:\n raise salt.exceptions.SaltCloudConfigError(\n 'The cloud provider alias \\'{0}\\' has an entry '\n 'missing the required setting of \\'driver\\''.format(\n alias\n )\n )\n\n driver = details['driver']\n\n if ':' in driver:\n # Weird, but...\n alias, driver = driver.split(':')\n if alias not in config['providers']:\n config['providers'][alias] = {}\n\n details['provider'] = '{0}:{1}'.format(alias, driver)\n config['providers'][alias][driver] = details\n\n # Migrate old configuration\n config = old_to_new(config)\n\n return config\n",
"def cloud_providers_config(path,\n env_var='SALT_CLOUD_PROVIDERS_CONFIG',\n defaults=None):\n '''\n Read in the salt cloud providers configuration file\n '''\n if defaults is None:\n defaults = PROVIDER_CONFIG_DEFAULTS\n\n overrides = salt.config.load_config(\n path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')\n )\n\n default_include = overrides.get(\n 'default_include', defaults['default_include']\n )\n include = overrides.get('include', [])\n\n overrides.update(\n salt.config.include_config(default_include, path, verbose=False)\n )\n overrides.update(\n salt.config.include_config(include, path, verbose=True)\n )\n return apply_cloud_providers_config(overrides, defaults)\n",
"def vm_profiles_config(path,\n providers,\n env_var='SALT_CLOUDVM_CONFIG',\n defaults=None):\n '''\n Read in the salt cloud VM config file\n '''\n if defaults is None:\n defaults = VM_CONFIG_DEFAULTS\n\n overrides = salt.config.load_config(\n path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')\n )\n\n default_include = overrides.get(\n 'default_include', defaults['default_include']\n )\n include = overrides.get('include', [])\n\n overrides.update(\n salt.config.include_config(default_include, path, verbose=False)\n )\n overrides.update(\n salt.config.include_config(include, path, verbose=True)\n )\n return apply_vm_profiles_config(providers, overrides, defaults)\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
apply_cloud_config
|
python
|
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
|
Return a cloud config
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2813-L2877
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def old_to_new(opts):\n providers = (\n 'AWS',\n 'CLOUDSTACK',\n 'DIGITALOCEAN',\n 'EC2',\n 'GOGRID',\n 'IBMSCE',\n 'JOYENT',\n 'LINODE',\n 'OPENSTACK',\n 'PARALLELS'\n 'RACKSPACE',\n 'SALTIFY'\n )\n\n for provider in providers:\n\n provider_config = {}\n for opt, val in opts.items():\n if provider in opt:\n value = val\n name = opt.split('.', 1)[1]\n provider_config[name] = value\n\n lprovider = provider.lower()\n if provider_config:\n provider_config['provider'] = lprovider\n opts.setdefault('providers', {})\n # provider alias\n opts['providers'][lprovider] = {}\n # provider alias, provider driver\n opts['providers'][lprovider][lprovider] = provider_config\n return opts\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
vm_profiles_config
|
python
|
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
|
Read in the salt cloud VM config file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L2916-L2941
|
[
"def include_config(include, orig_path, verbose, exit_on_config_errors=False):\n '''\n Parses extra configuration file(s) specified in an include list in the\n main config file.\n '''\n # Protect against empty option\n if not include:\n return {}\n\n if orig_path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if isinstance(include, six.string_types):\n include = [include]\n\n configuration = {}\n for path in include:\n # Allow for includes like ~/foo\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n path = os.path.join(os.path.dirname(orig_path), path)\n\n # Catch situation where user typos path in configuration; also warns\n # for empty include directory (which might be by design)\n glob_matches = glob.glob(path)\n if not glob_matches:\n if verbose:\n log.warning(\n 'Warning parsing configuration file: \"include\" path/glob '\n \"'%s' matches no files\", path\n )\n\n for fn_ in sorted(glob_matches):\n log.debug('Including configuration from \\'%s\\'', fn_)\n try:\n opts = _read_conf_file(fn_)\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n # Initialize default config if we wish to skip config errors\n opts = {}\n schedule = opts.get('schedule', {})\n if schedule and 'schedule' in configuration:\n configuration['schedule'].update(schedule)\n include = opts.get('include', [])\n if include:\n opts.update(include_config(include, fn_, verbose))\n\n salt.utils.dictupdate.update(configuration, opts, True, True)\n\n return configuration\n",
"def load_config(path, env_var, default_path=None, exit_on_config_errors=True):\n '''\n Returns configuration dict from parsing either the file described by\n ``path`` or the environment variable described by ``env_var`` as YAML.\n '''\n if path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if default_path is None:\n # This is most likely not being used from salt, i.e., could be salt-cloud\n # or salt-api which have not yet migrated to the new default_path\n # argument. Let's issue a warning message that the environ vars won't\n # work.\n import inspect\n previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)\n log.warning(\n \"The function '%s()' defined in '%s' is not yet using the \"\n \"new 'default_path' argument to `salt.config.load_config()`. \"\n \"As such, the '%s' environment variable will be ignored\",\n previous_frame.function, previous_frame.filename, env_var\n )\n # In this case, maintain old behavior\n default_path = DEFAULT_MASTER_OPTS['conf_file']\n\n # Default to the environment variable path, if it exists\n env_path = os.environ.get(env_var, path)\n if not env_path or not os.path.isfile(env_path):\n env_path = path\n # If non-default path from `-c`, use that over the env variable\n if path != default_path:\n env_path = path\n\n path = env_path\n\n # If the configuration file is missing, attempt to copy the template,\n # after removing the first header line.\n if not os.path.isfile(path):\n template = '{0}.template'.format(path)\n if os.path.isfile(template):\n log.debug('Writing %s based on %s', path, template)\n with salt.utils.files.fopen(path, 'w') as out:\n with salt.utils.files.fopen(template, 'r') as ifile:\n ifile.readline() # skip first line\n out.write(ifile.read())\n\n opts = {}\n\n if salt.utils.validate.path.is_readable(path):\n try:\n opts = _read_conf_file(path)\n opts['conf_file'] = path\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n log.debug('Missing configuration file: %s', path)\n\n return opts\n",
"def apply_vm_profiles_config(providers, overrides, defaults=None):\n if defaults is None:\n defaults = VM_CONFIG_DEFAULTS\n\n config = defaults.copy()\n if overrides:\n config.update(overrides)\n\n vms = {}\n\n for key, val in six.iteritems(config):\n if key in ('conf_file', 'include', 'default_include', 'user'):\n continue\n if not isinstance(val, dict):\n raise salt.exceptions.SaltCloudConfigError(\n 'The VM profiles configuration found in \\'{0[conf_file]}\\' is '\n 'not in the proper format'.format(config)\n )\n val['profile'] = key\n vms[key] = val\n\n # Is any VM profile extending data!?\n for profile, details in six.iteritems(vms.copy()):\n if 'extends' not in details:\n if ':' in details['provider']:\n alias, driver = details['provider'].split(':')\n if alias not in providers or driver not in providers[alias]:\n log.trace(\n 'The profile \\'%s\\' is defining \\'%s\\' '\n 'as the provider. Since there is no valid '\n 'configuration for that provider, the profile will be '\n 'removed from the available listing',\n profile, details['provider']\n )\n vms.pop(profile)\n continue\n\n if 'profiles' not in providers[alias][driver]:\n providers[alias][driver]['profiles'] = {}\n providers[alias][driver]['profiles'][profile] = details\n\n if details['provider'] not in providers:\n log.trace(\n 'The profile \\'%s\\' is defining \\'%s\\' as the '\n 'provider. Since there is no valid configuration for '\n 'that provider, the profile will be removed from the '\n 'available listing', profile, details['provider']\n )\n vms.pop(profile)\n continue\n\n driver = next(iter(list(providers[details['provider']].keys())))\n providers[details['provider']][driver].setdefault(\n 'profiles', {}).update({profile: details})\n details['provider'] = '{0[provider]}:{1}'.format(details, driver)\n vms[profile] = details\n\n continue\n\n extends = details.pop('extends')\n if extends not in vms:\n log.error(\n 'The \\'%s\\' profile is trying to extend data from \\'%s\\' '\n 'though \\'%s\\' is not defined in the salt profiles loaded '\n 'data. Not extending and removing from listing!',\n profile, extends, extends\n )\n vms.pop(profile)\n continue\n\n extended = deepcopy(vms.get(extends))\n extended.pop('profile')\n # Merge extended configuration with base profile\n extended = salt.utils.dictupdate.update(extended, details)\n\n if ':' not in extended['provider']:\n if extended['provider'] not in providers:\n log.trace(\n 'The profile \\'%s\\' is defining \\'%s\\' as the '\n 'provider. Since there is no valid configuration for '\n 'that provider, the profile will be removed from the '\n 'available listing', profile, extended['provider']\n )\n vms.pop(profile)\n continue\n\n driver = next(iter(list(providers[extended['provider']].keys())))\n providers[extended['provider']][driver].setdefault(\n 'profiles', {}).update({profile: extended})\n\n extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)\n else:\n alias, driver = extended['provider'].split(':')\n if alias not in providers or driver not in providers[alias]:\n log.trace(\n 'The profile \\'%s\\' is defining \\'%s\\' as '\n 'the provider. Since there is no valid configuration '\n 'for that provider, the profile will be removed from '\n 'the available listing', profile, extended['provider']\n )\n vms.pop(profile)\n continue\n\n providers[alias][driver].setdefault('profiles', {}).update(\n {profile: extended}\n )\n\n # Update the profile's entry with the extended data\n vms[profile] = extended\n\n return vms\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
cloud_providers_config
|
python
|
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
|
Read in the salt cloud providers configuration file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3057-L3081
|
[
"def include_config(include, orig_path, verbose, exit_on_config_errors=False):\n '''\n Parses extra configuration file(s) specified in an include list in the\n main config file.\n '''\n # Protect against empty option\n if not include:\n return {}\n\n if orig_path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if isinstance(include, six.string_types):\n include = [include]\n\n configuration = {}\n for path in include:\n # Allow for includes like ~/foo\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n path = os.path.join(os.path.dirname(orig_path), path)\n\n # Catch situation where user typos path in configuration; also warns\n # for empty include directory (which might be by design)\n glob_matches = glob.glob(path)\n if not glob_matches:\n if verbose:\n log.warning(\n 'Warning parsing configuration file: \"include\" path/glob '\n \"'%s' matches no files\", path\n )\n\n for fn_ in sorted(glob_matches):\n log.debug('Including configuration from \\'%s\\'', fn_)\n try:\n opts = _read_conf_file(fn_)\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n # Initialize default config if we wish to skip config errors\n opts = {}\n schedule = opts.get('schedule', {})\n if schedule and 'schedule' in configuration:\n configuration['schedule'].update(schedule)\n include = opts.get('include', [])\n if include:\n opts.update(include_config(include, fn_, verbose))\n\n salt.utils.dictupdate.update(configuration, opts, True, True)\n\n return configuration\n",
"def load_config(path, env_var, default_path=None, exit_on_config_errors=True):\n '''\n Returns configuration dict from parsing either the file described by\n ``path`` or the environment variable described by ``env_var`` as YAML.\n '''\n if path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if default_path is None:\n # This is most likely not being used from salt, i.e., could be salt-cloud\n # or salt-api which have not yet migrated to the new default_path\n # argument. Let's issue a warning message that the environ vars won't\n # work.\n import inspect\n previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)\n log.warning(\n \"The function '%s()' defined in '%s' is not yet using the \"\n \"new 'default_path' argument to `salt.config.load_config()`. \"\n \"As such, the '%s' environment variable will be ignored\",\n previous_frame.function, previous_frame.filename, env_var\n )\n # In this case, maintain old behavior\n default_path = DEFAULT_MASTER_OPTS['conf_file']\n\n # Default to the environment variable path, if it exists\n env_path = os.environ.get(env_var, path)\n if not env_path or not os.path.isfile(env_path):\n env_path = path\n # If non-default path from `-c`, use that over the env variable\n if path != default_path:\n env_path = path\n\n path = env_path\n\n # If the configuration file is missing, attempt to copy the template,\n # after removing the first header line.\n if not os.path.isfile(path):\n template = '{0}.template'.format(path)\n if os.path.isfile(template):\n log.debug('Writing %s based on %s', path, template)\n with salt.utils.files.fopen(path, 'w') as out:\n with salt.utils.files.fopen(template, 'r') as ifile:\n ifile.readline() # skip first line\n out.write(ifile.read())\n\n opts = {}\n\n if salt.utils.validate.path.is_readable(path):\n try:\n opts = _read_conf_file(path)\n opts['conf_file'] = path\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n log.debug('Missing configuration file: %s', path)\n\n return opts\n",
"def apply_cloud_providers_config(overrides, defaults=None):\n '''\n Apply the loaded cloud providers configuration.\n '''\n if defaults is None:\n defaults = PROVIDER_CONFIG_DEFAULTS\n\n config = defaults.copy()\n if overrides:\n config.update(overrides)\n\n # Is the user still using the old format in the new configuration file?!\n for name, settings in six.iteritems(config.copy()):\n if '.' in name:\n log.warning(\n 'Please switch to the new providers configuration syntax'\n )\n\n # Let's help out and migrate the data\n config = old_to_new(config)\n\n # old_to_new will migrate the old data into the 'providers' key of\n # the config dictionary. Let's map it correctly\n for prov_name, prov_settings in six.iteritems(config.pop('providers')):\n config[prov_name] = prov_settings\n break\n\n providers = {}\n ext_count = 0\n for key, val in six.iteritems(config):\n if key in ('conf_file', 'include', 'default_include', 'user'):\n continue\n\n if not isinstance(val, (list, tuple)):\n val = [val]\n else:\n # Need to check for duplicate cloud provider entries per \"alias\" or\n # we won't be able to properly reference it.\n handled_providers = set()\n for details in val:\n if 'driver' not in details:\n if 'extends' not in details:\n log.error(\n 'Please check your cloud providers configuration. '\n 'There\\'s no \\'driver\\' nor \\'extends\\' definition '\n 'referenced.'\n )\n continue\n\n if details['driver'] in handled_providers:\n log.error(\n 'You can only have one entry per cloud provider. For '\n 'example, if you have a cloud provider configuration '\n 'section named, \\'production\\', you can only have a '\n 'single entry for EC2, Joyent, Openstack, and so '\n 'forth.'\n )\n raise salt.exceptions.SaltCloudConfigError(\n 'The cloud provider alias \\'{0}\\' has multiple entries '\n 'for the \\'{1[driver]}\\' driver.'.format(key, details)\n )\n handled_providers.add(details['driver'])\n\n for entry in val:\n\n if 'driver' not in entry:\n entry['driver'] = '-only-extendable-{0}'.format(ext_count)\n ext_count += 1\n\n if key not in providers:\n providers[key] = {}\n\n provider = entry['driver']\n if provider not in providers[key]:\n providers[key][provider] = entry\n\n # Is any provider extending data!?\n while True:\n keep_looping = False\n for provider_alias, entries in six.iteritems(providers.copy()):\n for driver, details in six.iteritems(entries):\n # Set a holder for the defined profiles\n providers[provider_alias][driver]['profiles'] = {}\n\n if 'extends' not in details:\n continue\n\n extends = details.pop('extends')\n\n if ':' in extends:\n alias, provider = extends.split(':')\n if alias not in providers:\n raise salt.exceptions.SaltCloudConfigError(\n 'The \\'{0}\\' cloud provider entry in \\'{1}\\' is '\n 'trying to extend data from \\'{2}\\' though '\n '\\'{2}\\' is not defined in the salt cloud '\n 'providers loaded data.'.format(\n details['driver'],\n provider_alias,\n alias\n )\n )\n\n if provider not in providers.get(alias):\n raise salt.exceptions.SaltCloudConfigError(\n 'The \\'{0}\\' cloud provider entry in \\'{1}\\' is '\n 'trying to extend data from \\'{2}:{3}\\' though '\n '\\'{3}\\' is not defined in \\'{1}\\''.format(\n details['driver'],\n provider_alias,\n alias,\n provider\n )\n )\n details['extends'] = '{0}:{1}'.format(alias, provider)\n # change provider details '-only-extendable-' to extended\n # provider name\n details['driver'] = provider\n elif providers.get(extends):\n raise salt.exceptions.SaltCloudConfigError(\n 'The \\'{0}\\' cloud provider entry in \\'{1}\\' is '\n 'trying to extend from \\'{2}\\' and no provider was '\n 'specified. Not extending!'.format(\n details['driver'], provider_alias, extends\n )\n )\n elif extends not in providers:\n raise salt.exceptions.SaltCloudConfigError(\n 'The \\'{0}\\' cloud provider entry in \\'{1}\\' is '\n 'trying to extend data from \\'{2}\\' though \\'{2}\\' '\n 'is not defined in the salt cloud providers loaded '\n 'data.'.format(\n details['driver'], provider_alias, extends\n )\n )\n else:\n if driver in providers.get(extends):\n details['extends'] = '{0}:{1}'.format(extends, driver)\n elif '-only-extendable-' in providers.get(extends):\n details['extends'] = '{0}:{1}'.format(\n extends, '-only-extendable-{0}'.format(ext_count)\n )\n else:\n # We're still not aware of what we're trying to extend\n # from. Let's try on next iteration\n details['extends'] = extends\n keep_looping = True\n if not keep_looping:\n break\n\n while True:\n # Merge provided extends\n keep_looping = False\n for alias, entries in six.iteritems(providers.copy()):\n for driver, details in six.iteritems(entries):\n\n if 'extends' not in details:\n # Extends resolved or non existing, continue!\n continue\n\n if 'extends' in details['extends']:\n # Since there's a nested extends, resolve this one in the\n # next iteration\n keep_looping = True\n continue\n\n # Let's get a reference to what we're supposed to extend\n extends = details.pop('extends')\n # Split the setting in (alias, driver)\n ext_alias, ext_driver = extends.split(':')\n # Grab a copy of what should be extended\n extended = providers.get(ext_alias).get(ext_driver).copy()\n # Merge the data to extend with the details\n extended = salt.utils.dictupdate.update(extended, details)\n # Update the providers dictionary with the merged data\n providers[alias][driver] = extended\n # Update name of the driver, now that it's populated with extended information\n if driver.startswith('-only-extendable-'):\n providers[alias][ext_driver] = providers[alias][driver]\n # Delete driver with old name to maintain dictionary size\n del providers[alias][driver]\n\n if not keep_looping:\n break\n\n # Now clean up any providers entry that was just used to be a data tree to\n # extend from\n for provider_alias, entries in six.iteritems(providers.copy()):\n for driver, details in six.iteritems(entries.copy()):\n if not driver.startswith('-only-extendable-'):\n continue\n\n log.info(\n \"There's at least one cloud driver under the '%s' \"\n 'cloud provider alias which does not have the required '\n \"'driver' setting. Removing it from the available \"\n 'providers listing.', provider_alias\n )\n providers[provider_alias].pop(driver)\n\n if not providers[provider_alias]:\n providers.pop(provider_alias)\n\n return providers\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
apply_cloud_providers_config
|
python
|
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
|
Apply the loaded cloud providers configuration.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3084-L3287
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def update(dest, upd, recursive_update=True, merge_lists=False):\n '''\n Recursive version of the default dict.update\n\n Merges upd recursively into dest\n\n If recursive_update=False, will use the classic dict.update, or fall back\n on a manual merge (helpful for non-dict types like FunctionWrapper)\n\n If merge_lists=True, will aggregate list object types instead of replace.\n The list in ``upd`` is added to the list in ``dest``, so the resulting list\n is ``dest[key] + upd[key]``. This behavior is only activated when\n recursive_update=True. By default merge_lists=False.\n\n .. versionchanged: 2016.11.6\n When merging lists, duplicate values are removed. Values already\n present in the ``dest`` list are not added from the ``upd`` list.\n '''\n if (not isinstance(dest, Mapping)) \\\n or (not isinstance(upd, Mapping)):\n raise TypeError('Cannot update using non-dict types in dictupdate.update()')\n updkeys = list(upd.keys())\n if not set(list(dest.keys())) & set(updkeys):\n recursive_update = False\n if recursive_update:\n for key in updkeys:\n val = upd[key]\n try:\n dest_subkey = dest.get(key, None)\n except AttributeError:\n dest_subkey = None\n if isinstance(dest_subkey, Mapping) \\\n and isinstance(val, Mapping):\n ret = update(dest_subkey, val, merge_lists=merge_lists)\n dest[key] = ret\n elif isinstance(dest_subkey, list) and isinstance(val, list):\n if merge_lists:\n merged = copy.deepcopy(dest_subkey)\n merged.extend([x for x in val if x not in merged])\n dest[key] = merged\n else:\n dest[key] = upd[key]\n else:\n dest[key] = upd[key]\n return dest\n try:\n for k in upd:\n dest[k] = upd[k]\n except AttributeError:\n # this mapping is not a dict\n for k in upd:\n dest[k] = upd[k]\n return dest\n",
"def old_to_new(opts):\n providers = (\n 'AWS',\n 'CLOUDSTACK',\n 'DIGITALOCEAN',\n 'EC2',\n 'GOGRID',\n 'IBMSCE',\n 'JOYENT',\n 'LINODE',\n 'OPENSTACK',\n 'PARALLELS'\n 'RACKSPACE',\n 'SALTIFY'\n )\n\n for provider in providers:\n\n provider_config = {}\n for opt, val in opts.items():\n if provider in opt:\n value = val\n name = opt.split('.', 1)[1]\n provider_config[name] = value\n\n lprovider = provider.lower()\n if provider_config:\n provider_config['provider'] = lprovider\n opts.setdefault('providers', {})\n # provider alias\n opts['providers'][lprovider] = {}\n # provider alias, provider driver\n opts['providers'][lprovider][lprovider] = provider_config\n return opts\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
get_cloud_config_value
|
python
|
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
|
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3290-L3364
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
is_provider_configured
|
python
|
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
|
Check and return the first matching and fully configured cloud provider
configuration.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3367-L3421
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
is_profile_configured
|
python
|
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
|
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3424-L3499
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
check_driver_dependencies
|
python
|
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
|
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3502-L3523
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_cache_id
|
python
|
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
|
Helper function, writes minion id to a cache file.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3528-L3547
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
call_id_function
|
python
|
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
|
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3550-L3600
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
remove_domain_from_fqdn
|
python
|
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
|
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3603-L3620
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
get_id
|
python
|
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
|
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3623-L3690
|
[
"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",
"def call_id_function(opts):\n '''\n Evaluate the function that determines the ID if the 'id_function'\n option is set and return the result\n '''\n if opts.get('id'):\n return opts['id']\n\n # Import 'salt.loader' here to avoid a circular dependency\n import salt.loader as loader\n\n if isinstance(opts['id_function'], six.string_types):\n mod_fun = opts['id_function']\n fun_kwargs = {}\n elif isinstance(opts['id_function'], dict):\n mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))\n if fun_kwargs is None:\n fun_kwargs = {}\n else:\n log.error('\\'id_function\\' option is neither a string nor a dictionary')\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n\n # split module and function and try loading the module\n mod, fun = mod_fun.split('.')\n if not opts.get('grains'):\n # Get grains for use by the module\n opts['grains'] = loader.grains(opts)\n\n try:\n id_mod = loader.raw_mod(opts, mod, fun)\n if not id_mod:\n raise KeyError\n # we take whatever the module returns as the minion ID\n newid = id_mod[mod_fun](**fun_kwargs)\n if not isinstance(newid, six.string_types) or not newid:\n log.error(\n 'Function %s returned value \"%s\" of type %s instead of string',\n mod_fun, newid, type(newid)\n )\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n log.info('Evaluated minion ID from module: %s', mod_fun)\n return newid\n except TypeError:\n log.error(\n 'Function arguments %s are incorrect for function %s',\n fun_kwargs, mod_fun\n )\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n except KeyError:\n log.error('Failed to load module %s', mod_fun)\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n",
"def generate_minion_id():\n '''\n Return only first element of the hostname from all possible list.\n\n :return:\n '''\n try:\n ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first())\n except TypeError:\n ret = None\n return ret or 'localhost'\n",
"def is_ipv4(ip):\n '''\n Returns a bool telling if the value passed to it was a valid IPv4 address\n '''\n try:\n return ipaddress.ip_address(ip).version == 4\n except ValueError:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_update_ssl_config
|
python
|
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
|
Resolves string names to integer constant in ssl configuration.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3693-L3714
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_adjust_log_file_override
|
python
|
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
|
Adjusts the log_file based on the log_dir override
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3717-L3732
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
apply_minion_config
|
python
|
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
|
Returns minion configurations dict.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3735-L3864
|
[
"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 _validate_pillar_roots(pillar_roots):\n '''\n If the pillar_roots option has a key that is None then we will error out,\n just replace it with an empty list\n '''\n if not isinstance(pillar_roots, dict):\n log.warning('The pillar_roots parameter is not properly formatted,'\n ' using defaults')\n return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}\n return _normalize_roots(pillar_roots)\n",
"def _validate_file_roots(file_roots):\n '''\n If the file_roots option has a key that is None then we will error out,\n just replace it with an empty list\n '''\n if not isinstance(file_roots, dict):\n log.warning('The file_roots parameter is not properly formatted,'\n ' using defaults')\n return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}\n return _normalize_roots(file_roots)\n",
"def _append_domain(opts):\n '''\n Append a domain to the existing id if it doesn't already exist\n '''\n # Domain already exists\n if opts['id'].endswith(opts['append_domain']):\n return opts['id']\n # Trailing dot should mean an FQDN that is terminated, leave it alone.\n if opts['id'].endswith('.'):\n return opts['id']\n return '{0[id]}.{0[append_domain]}'.format(opts)\n",
"def prepend_root_dir(opts, path_options):\n '''\n Prepends the options that represent filesystem paths with value of the\n 'root_dir' option.\n '''\n root_dir = os.path.abspath(opts['root_dir'])\n def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)\n for path_option in path_options:\n if path_option in opts:\n path = opts[path_option]\n tmp_path_def_root_dir = None\n tmp_path_root_dir = None\n # When running testsuite, salt.syspaths.ROOT_DIR is often empty\n if path == def_root_dir or path.startswith(def_root_dir + os.sep):\n # Remove the default root dir prefix\n tmp_path_def_root_dir = path[len(def_root_dir):]\n if root_dir and (path == root_dir or\n path.startswith(root_dir + os.sep)):\n # Remove the root dir prefix\n tmp_path_root_dir = path[len(root_dir):]\n if tmp_path_def_root_dir and not tmp_path_root_dir:\n # Just the default root dir matched\n path = tmp_path_def_root_dir\n elif tmp_path_root_dir and not tmp_path_def_root_dir:\n # Just the root dir matched\n path = tmp_path_root_dir\n elif tmp_path_def_root_dir and tmp_path_root_dir:\n # In this case both the default root dir and the override root\n # dir matched; this means that either\n # def_root_dir is a substring of root_dir or vice versa\n # We must choose the most specific path\n if def_root_dir in root_dir:\n path = tmp_path_root_dir\n else:\n path = tmp_path_def_root_dir\n elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:\n # In windows, os.path.isabs resolves '/' to 'C:\\\\' or whatever\n # the root drive is. This elif prevents the next from being\n # hit, so that the root_dir is prefixed in cases where the\n # drive is not prefixed on a config option\n pass\n elif os.path.isabs(path):\n # Absolute path (not default or overridden root_dir)\n # No prepending required\n continue\n # Prepending the root dir\n opts[path_option] = salt.utils.path.join(root_dir, path)\n",
"def insert_system_path(opts, paths):\n '''\n Inserts path into python path taking into consideration 'root_dir' option.\n '''\n if isinstance(paths, six.string_types):\n paths = [paths]\n for path in paths:\n path_options = {'path': path, 'root_dir': opts['root_dir']}\n prepend_root_dir(path_options, path_options)\n if (os.path.isdir(path_options['path'])\n and path_options['path'] not in sys.path):\n sys.path.insert(0, path_options['path'])\n",
"def get_id(opts, cache_minion_id=False):\n '''\n Guess the id of the minion.\n\n If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.\n If no minion id is configured, use multiple sources to find a FQDN.\n If no FQDN is found you may get an ip address.\n\n Returns two values: the detected ID, and a boolean value noting whether or\n not an IP address is being used for the ID.\n '''\n if opts['root_dir'] is None:\n root_dir = salt.syspaths.ROOT_DIR\n else:\n root_dir = opts['root_dir']\n\n config_dir = salt.syspaths.CONFIG_DIR\n if config_dir.startswith(salt.syspaths.ROOT_DIR):\n config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]\n\n # Check for cached minion ID\n id_cache = os.path.join(root_dir,\n config_dir.lstrip(os.path.sep),\n 'minion_id')\n\n if opts.get('minion_id_caching', True):\n try:\n with salt.utils.files.fopen(id_cache) as idf:\n name = salt.utils.stringutils.to_unicode(idf.readline().strip())\n bname = salt.utils.stringutils.to_bytes(name)\n if bname.startswith(codecs.BOM): # Remove BOM if exists\n name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))\n if name and name != 'localhost':\n log.debug('Using cached minion ID from %s: %s', id_cache, name)\n return name, False\n except (IOError, OSError):\n pass\n if '__role' in opts and opts.get('__role') == 'minion':\n log.debug(\n 'Guessing ID. The id can be explicitly set in %s',\n os.path.join(salt.syspaths.CONFIG_DIR, 'minion')\n )\n\n if opts.get('id_function'):\n newid = call_id_function(opts)\n else:\n newid = salt.utils.network.generate_minion_id()\n\n if opts.get('minion_id_lowercase'):\n newid = newid.lower()\n log.debug('Changed minion id %s to lowercase.', newid)\n\n # Optionally remove one or many domains in a generated minion id\n if opts.get('minion_id_remove_domain'):\n newid = remove_domain_from_fqdn(opts, newid)\n\n if '__role' in opts and opts.get('__role') == 'minion':\n if opts.get('id_function'):\n log.debug(\n 'Found minion id from external function %s: %s',\n opts['id_function'], newid\n )\n else:\n log.debug('Found minion id from generate_minion_id(): %s', newid)\n if cache_minion_id and opts.get('minion_id_caching', True):\n _cache_id(newid, id_cache)\n is_ipv4 = salt.utils.network.is_ipv4(newid)\n return newid, is_ipv4\n",
"def _update_ssl_config(opts):\n '''\n Resolves string names to integer constant in ssl configuration.\n '''\n if opts['ssl'] in (None, False):\n opts['ssl'] = None\n return\n if opts['ssl'] is True:\n opts['ssl'] = {}\n return\n import ssl\n for key, prefix in (('cert_reqs', 'CERT_'),\n ('ssl_version', 'PROTOCOL_')):\n val = opts['ssl'].get(key)\n if val is None:\n continue\n if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):\n message = 'SSL option \\'{0}\\' must be set to one of the following values: \\'{1}\\'.' \\\n .format(key, '\\', \\''.join([val for val in dir(ssl) if val.startswith(prefix)]))\n log.error(message)\n raise salt.exceptions.SaltConfigurationError(message)\n opts['ssl'][key] = getattr(ssl, val)\n",
"def _adjust_log_file_override(overrides, default_log_file):\n '''\n Adjusts the log_file based on the log_dir override\n '''\n if overrides.get('log_dir'):\n # Adjust log_file if a log_dir override is introduced\n if overrides.get('log_file'):\n if not os.path.isabs(overrides['log_file']):\n # Prepend log_dir if log_file is relative\n overrides['log_file'] = os.path.join(overrides['log_dir'],\n overrides['log_file'])\n else:\n # Create the log_file override\n overrides['log_file'] = \\\n os.path.join(overrides['log_dir'],\n os.path.basename(default_log_file))\n",
"def _update_discovery_config(opts):\n '''\n Update discovery config for all instances.\n\n :param opts:\n :return:\n '''\n if opts.get('discovery') not in (None, False):\n if opts['discovery'] is True:\n opts['discovery'] = {}\n discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}\n for key in opts['discovery']:\n if key not in discovery_config:\n raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))\n if opts.get('__role') != 'minion':\n for key in ['attempts', 'pause', 'match']:\n del discovery_config[key]\n opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
_update_discovery_config
|
python
|
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
|
Update discovery config for all instances.
:param opts:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3867-L3884
| null |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
master_config
|
python
|
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
|
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3887-L3930
|
[
"def include_config(include, orig_path, verbose, exit_on_config_errors=False):\n '''\n Parses extra configuration file(s) specified in an include list in the\n main config file.\n '''\n # Protect against empty option\n if not include:\n return {}\n\n if orig_path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if isinstance(include, six.string_types):\n include = [include]\n\n configuration = {}\n for path in include:\n # Allow for includes like ~/foo\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n path = os.path.join(os.path.dirname(orig_path), path)\n\n # Catch situation where user typos path in configuration; also warns\n # for empty include directory (which might be by design)\n glob_matches = glob.glob(path)\n if not glob_matches:\n if verbose:\n log.warning(\n 'Warning parsing configuration file: \"include\" path/glob '\n \"'%s' matches no files\", path\n )\n\n for fn_ in sorted(glob_matches):\n log.debug('Including configuration from \\'%s\\'', fn_)\n try:\n opts = _read_conf_file(fn_)\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n # Initialize default config if we wish to skip config errors\n opts = {}\n schedule = opts.get('schedule', {})\n if schedule and 'schedule' in configuration:\n configuration['schedule'].update(schedule)\n include = opts.get('include', [])\n if include:\n opts.update(include_config(include, fn_, verbose))\n\n salt.utils.dictupdate.update(configuration, opts, True, True)\n\n return configuration\n",
"def is_dictlist(data):\n '''\n Returns True if data is a list of one-element dicts (as found in many SLS\n schemas), otherwise returns False\n '''\n if isinstance(data, list):\n for element in data:\n if isinstance(element, dict):\n if len(element) != 1:\n return False\n else:\n return False\n return True\n return False\n",
"def _validate_opts(opts):\n '''\n Check that all of the types of values passed into the config are\n of the right types\n '''\n def format_multi_opt(valid_type):\n try:\n num_types = len(valid_type)\n except TypeError:\n # Bare type name won't have a length, return the name of the type\n # passed.\n return valid_type.__name__\n else:\n def get_types(types, type_tuple):\n for item in type_tuple:\n if isinstance(item, tuple):\n get_types(types, item)\n else:\n try:\n types.append(item.__name__)\n except AttributeError:\n log.warning(\n 'Unable to interpret type %s while validating '\n 'configuration', item\n )\n types = []\n get_types(types, valid_type)\n\n ret = ', '.join(types[:-1])\n ret += ' or ' + types[-1]\n return ret\n\n errors = []\n\n err = (\n 'Config option \\'{0}\\' with value {1} has an invalid type of {2}, a '\n '{3} is required for this option'\n )\n for key, val in six.iteritems(opts):\n if key in VALID_OPTS:\n if val is None:\n if VALID_OPTS[key] is None:\n continue\n else:\n try:\n if None in VALID_OPTS[key]:\n continue\n except TypeError:\n # VALID_OPTS[key] is not iterable and not None\n pass\n\n if isinstance(val, VALID_OPTS[key]):\n continue\n\n # We don't know what data type sdb will return at run-time so we\n # simply cannot check it for correctness here at start-time.\n if isinstance(val, six.string_types) and val.startswith('sdb://'):\n continue\n\n if hasattr(VALID_OPTS[key], '__call__'):\n try:\n VALID_OPTS[key](val)\n if isinstance(val, (list, dict)):\n # We'll only get here if VALID_OPTS[key] is str or\n # bool, and the passed value is a list/dict. Attempting\n # to run int() or float() on a list/dict will raise an\n # exception, but running str() or bool() on it will\n # pass despite not being the correct type.\n errors.append(\n err.format(\n key,\n val,\n type(val).__name__,\n VALID_OPTS[key].__name__\n )\n )\n except (TypeError, ValueError):\n errors.append(\n err.format(key,\n val,\n type(val).__name__,\n VALID_OPTS[key].__name__)\n )\n continue\n\n errors.append(\n err.format(key,\n val,\n type(val).__name__,\n format_multi_opt(VALID_OPTS[key]))\n )\n\n # Convert list to comma-delimited string for 'return' config option\n if isinstance(opts.get('return'), list):\n opts['return'] = ','.join(opts['return'])\n\n for error in errors:\n log.warning(error)\n if errors:\n return False\n return True\n",
"def _validate_ssh_minion_opts(opts):\n '''\n Ensure we're not using any invalid ssh_minion_opts. We want to make sure\n that the ssh_minion_opts does not override any pillar or fileserver options\n inherited from the master config. To add other items, modify the if\n statement in the for loop below.\n '''\n ssh_minion_opts = opts.get('ssh_minion_opts', {})\n if not isinstance(ssh_minion_opts, dict):\n log.error('Invalidly-formatted ssh_minion_opts')\n opts.pop('ssh_minion_opts')\n\n for opt_name in list(ssh_minion_opts):\n if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \\\n or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \\\n or opt_name in ('fileserver_backend',):\n log.warning(\n '\\'%s\\' is not a valid ssh_minion_opts parameter, ignoring',\n opt_name\n )\n ssh_minion_opts.pop(opt_name)\n",
"def load_config(path, env_var, default_path=None, exit_on_config_errors=True):\n '''\n Returns configuration dict from parsing either the file described by\n ``path`` or the environment variable described by ``env_var`` as YAML.\n '''\n if path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if default_path is None:\n # This is most likely not being used from salt, i.e., could be salt-cloud\n # or salt-api which have not yet migrated to the new default_path\n # argument. Let's issue a warning message that the environ vars won't\n # work.\n import inspect\n previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)\n log.warning(\n \"The function '%s()' defined in '%s' is not yet using the \"\n \"new 'default_path' argument to `salt.config.load_config()`. \"\n \"As such, the '%s' environment variable will be ignored\",\n previous_frame.function, previous_frame.filename, env_var\n )\n # In this case, maintain old behavior\n default_path = DEFAULT_MASTER_OPTS['conf_file']\n\n # Default to the environment variable path, if it exists\n env_path = os.environ.get(env_var, path)\n if not env_path or not os.path.isfile(env_path):\n env_path = path\n # If non-default path from `-c`, use that over the env variable\n if path != default_path:\n env_path = path\n\n path = env_path\n\n # If the configuration file is missing, attempt to copy the template,\n # after removing the first header line.\n if not os.path.isfile(path):\n template = '{0}.template'.format(path)\n if os.path.isfile(template):\n log.debug('Writing %s based on %s', path, template)\n with salt.utils.files.fopen(path, 'w') as out:\n with salt.utils.files.fopen(template, 'r') as ifile:\n ifile.readline() # skip first line\n out.write(ifile.read())\n\n opts = {}\n\n if salt.utils.validate.path.is_readable(path):\n try:\n opts = _read_conf_file(path)\n opts['conf_file'] = path\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n log.debug('Missing configuration file: %s', path)\n\n return opts\n",
"def apply_sdb(opts, sdb_opts=None):\n '''\n Recurse for sdb:// links for opts\n '''\n # Late load of SDB to keep CLI light\n import salt.utils.sdb\n if sdb_opts is None:\n sdb_opts = opts\n if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):\n return salt.utils.sdb.sdb_get(sdb_opts, opts)\n elif isinstance(sdb_opts, dict):\n for key, value in six.iteritems(sdb_opts):\n if value is None:\n continue\n sdb_opts[key] = apply_sdb(opts, value)\n elif isinstance(sdb_opts, list):\n for key, value in enumerate(sdb_opts):\n if value is None:\n continue\n sdb_opts[key] = apply_sdb(opts, value)\n\n return sdb_opts\n",
"def apply_master_config(overrides=None, defaults=None):\n '''\n Returns master configurations dict.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n if overrides is None:\n overrides = {}\n\n opts = defaults.copy()\n opts['__role'] = 'master'\n _adjust_log_file_override(overrides, defaults['log_file'])\n if overrides:\n opts.update(overrides)\n\n opts['__cli'] = salt.utils.stringutils.to_unicode(\n os.path.basename(sys.argv[0])\n )\n\n if 'environment' in opts:\n if opts['saltenv'] is not None:\n log.warning(\n 'The \\'saltenv\\' and \\'environment\\' master config options '\n 'cannot both be used. Ignoring \\'environment\\' in favor of '\n '\\'saltenv\\'.',\n )\n # Set environment to saltenv in case someone's custom runner is\n # refrencing __opts__['environment']\n opts['environment'] = opts['saltenv']\n else:\n log.warning(\n 'The \\'environment\\' master config option has been renamed '\n 'to \\'saltenv\\'. Using %s as the \\'saltenv\\' config value.',\n opts['environment']\n )\n opts['saltenv'] = opts['environment']\n\n if six.PY2 and 'rest_cherrypy' in opts:\n # CherryPy is not unicode-compatible\n opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])\n\n for idx, val in enumerate(opts['fileserver_backend']):\n if val in ('git', 'hg', 'svn', 'minion'):\n new_val = val + 'fs'\n log.debug(\n 'Changed %s to %s in master opts\\' fileserver_backend list',\n val, new_val\n )\n opts['fileserver_backend'][idx] = new_val\n\n if len(opts['sock_dir']) > len(opts['cachedir']) + 10:\n opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')\n\n opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')\n opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')\n # Make sure ext_mods gets set if it is an untrue value\n # (here to catch older bad configs)\n opts['extension_modules'] = (\n opts.get('extension_modules') or\n os.path.join(opts['cachedir'], 'extmods')\n )\n # Set up the utils_dirs location from the extension_modules location\n opts['utils_dirs'] = (\n opts.get('utils_dirs') or\n [os.path.join(opts['extension_modules'], 'utils')]\n )\n\n # Insert all 'utils_dirs' directories to the system path\n insert_system_path(opts, opts['utils_dirs'])\n\n if overrides.get('ipc_write_buffer', '') == 'dynamic':\n opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER\n\n using_ip_for_id = False\n append_master = False\n if not opts.get('id'):\n opts['id'], using_ip_for_id = get_id(\n opts,\n cache_minion_id=None)\n append_master = True\n\n # it does not make sense to append a domain to an IP based id\n if not using_ip_for_id and 'append_domain' in opts:\n opts['id'] = _append_domain(opts)\n if append_master:\n opts['id'] += '_master'\n\n # Prepend root_dir to other paths\n prepend_root_dirs = [\n 'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',\n 'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',\n 'sqlite_queue_dir', 'autosign_grains_dir'\n ]\n\n # These can be set to syslog, so, not actual paths on the system\n for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):\n log_setting = opts.get(config_key, '')\n if log_setting is None:\n continue\n\n if urlparse(log_setting).scheme == '':\n prepend_root_dirs.append(config_key)\n\n prepend_root_dir(opts, prepend_root_dirs)\n\n # Enabling open mode requires that the value be set to True, and\n # nothing else!\n opts['open_mode'] = opts['open_mode'] is True\n opts['auto_accept'] = opts['auto_accept'] is True\n opts['file_roots'] = _validate_file_roots(opts['file_roots'])\n opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])\n\n if opts['file_ignore_regex']:\n # If file_ignore_regex was given, make sure it's wrapped in a list.\n # Only keep valid regex entries for improved performance later on.\n if isinstance(opts['file_ignore_regex'], six.string_types):\n ignore_regex = [opts['file_ignore_regex']]\n elif isinstance(opts['file_ignore_regex'], list):\n ignore_regex = opts['file_ignore_regex']\n\n opts['file_ignore_regex'] = []\n for regex in ignore_regex:\n try:\n # Can't store compiled regex itself in opts (breaks\n # serialization)\n re.compile(regex)\n opts['file_ignore_regex'].append(regex)\n except Exception:\n log.warning(\n 'Unable to parse file_ignore_regex. Skipping: %s',\n regex\n )\n\n if opts['file_ignore_glob']:\n # If file_ignore_glob was given, make sure it's wrapped in a list.\n if isinstance(opts['file_ignore_glob'], six.string_types):\n opts['file_ignore_glob'] = [opts['file_ignore_glob']]\n\n # Let's make sure `worker_threads` does not drop below 3 which has proven\n # to make `salt.modules.publish` not work under the test-suite.\n if opts['worker_threads'] < 3 and opts.get('peer', None):\n log.warning(\n \"The 'worker_threads' setting in '%s' cannot be lower than \"\n '3. Resetting it to the default value of 3.', opts['conf_file']\n )\n opts['worker_threads'] = 3\n\n opts.setdefault('pillar_source_merging_strategy', 'smart')\n\n # Make sure hash_type is lowercase\n opts['hash_type'] = opts['hash_type'].lower()\n\n # Check and update TLS/SSL configuration\n _update_ssl_config(opts)\n _update_discovery_config(opts)\n\n return opts\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
apply_master_config
|
python
|
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
|
Returns master configurations dict.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L3933-L4089
|
[
"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 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 _validate_file_roots(file_roots):\n '''\n If the file_roots option has a key that is None then we will error out,\n just replace it with an empty list\n '''\n if not isinstance(file_roots, dict):\n log.warning('The file_roots parameter is not properly formatted,'\n ' using defaults')\n return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}\n return _normalize_roots(file_roots)\n",
"def _append_domain(opts):\n '''\n Append a domain to the existing id if it doesn't already exist\n '''\n # Domain already exists\n if opts['id'].endswith(opts['append_domain']):\n return opts['id']\n # Trailing dot should mean an FQDN that is terminated, leave it alone.\n if opts['id'].endswith('.'):\n return opts['id']\n return '{0[id]}.{0[append_domain]}'.format(opts)\n",
"def prepend_root_dir(opts, path_options):\n '''\n Prepends the options that represent filesystem paths with value of the\n 'root_dir' option.\n '''\n root_dir = os.path.abspath(opts['root_dir'])\n def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)\n for path_option in path_options:\n if path_option in opts:\n path = opts[path_option]\n tmp_path_def_root_dir = None\n tmp_path_root_dir = None\n # When running testsuite, salt.syspaths.ROOT_DIR is often empty\n if path == def_root_dir or path.startswith(def_root_dir + os.sep):\n # Remove the default root dir prefix\n tmp_path_def_root_dir = path[len(def_root_dir):]\n if root_dir and (path == root_dir or\n path.startswith(root_dir + os.sep)):\n # Remove the root dir prefix\n tmp_path_root_dir = path[len(root_dir):]\n if tmp_path_def_root_dir and not tmp_path_root_dir:\n # Just the default root dir matched\n path = tmp_path_def_root_dir\n elif tmp_path_root_dir and not tmp_path_def_root_dir:\n # Just the root dir matched\n path = tmp_path_root_dir\n elif tmp_path_def_root_dir and tmp_path_root_dir:\n # In this case both the default root dir and the override root\n # dir matched; this means that either\n # def_root_dir is a substring of root_dir or vice versa\n # We must choose the most specific path\n if def_root_dir in root_dir:\n path = tmp_path_root_dir\n else:\n path = tmp_path_def_root_dir\n elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:\n # In windows, os.path.isabs resolves '/' to 'C:\\\\' or whatever\n # the root drive is. This elif prevents the next from being\n # hit, so that the root_dir is prefixed in cases where the\n # drive is not prefixed on a config option\n pass\n elif os.path.isabs(path):\n # Absolute path (not default or overridden root_dir)\n # No prepending required\n continue\n # Prepending the root dir\n opts[path_option] = salt.utils.path.join(root_dir, path)\n",
"def insert_system_path(opts, paths):\n '''\n Inserts path into python path taking into consideration 'root_dir' option.\n '''\n if isinstance(paths, six.string_types):\n paths = [paths]\n for path in paths:\n path_options = {'path': path, 'root_dir': opts['root_dir']}\n prepend_root_dir(path_options, path_options)\n if (os.path.isdir(path_options['path'])\n and path_options['path'] not in sys.path):\n sys.path.insert(0, path_options['path'])\n",
"def get_id(opts, cache_minion_id=False):\n '''\n Guess the id of the minion.\n\n If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.\n If no minion id is configured, use multiple sources to find a FQDN.\n If no FQDN is found you may get an ip address.\n\n Returns two values: the detected ID, and a boolean value noting whether or\n not an IP address is being used for the ID.\n '''\n if opts['root_dir'] is None:\n root_dir = salt.syspaths.ROOT_DIR\n else:\n root_dir = opts['root_dir']\n\n config_dir = salt.syspaths.CONFIG_DIR\n if config_dir.startswith(salt.syspaths.ROOT_DIR):\n config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]\n\n # Check for cached minion ID\n id_cache = os.path.join(root_dir,\n config_dir.lstrip(os.path.sep),\n 'minion_id')\n\n if opts.get('minion_id_caching', True):\n try:\n with salt.utils.files.fopen(id_cache) as idf:\n name = salt.utils.stringutils.to_unicode(idf.readline().strip())\n bname = salt.utils.stringutils.to_bytes(name)\n if bname.startswith(codecs.BOM): # Remove BOM if exists\n name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))\n if name and name != 'localhost':\n log.debug('Using cached minion ID from %s: %s', id_cache, name)\n return name, False\n except (IOError, OSError):\n pass\n if '__role' in opts and opts.get('__role') == 'minion':\n log.debug(\n 'Guessing ID. The id can be explicitly set in %s',\n os.path.join(salt.syspaths.CONFIG_DIR, 'minion')\n )\n\n if opts.get('id_function'):\n newid = call_id_function(opts)\n else:\n newid = salt.utils.network.generate_minion_id()\n\n if opts.get('minion_id_lowercase'):\n newid = newid.lower()\n log.debug('Changed minion id %s to lowercase.', newid)\n\n # Optionally remove one or many domains in a generated minion id\n if opts.get('minion_id_remove_domain'):\n newid = remove_domain_from_fqdn(opts, newid)\n\n if '__role' in opts and opts.get('__role') == 'minion':\n if opts.get('id_function'):\n log.debug(\n 'Found minion id from external function %s: %s',\n opts['id_function'], newid\n )\n else:\n log.debug('Found minion id from generate_minion_id(): %s', newid)\n if cache_minion_id and opts.get('minion_id_caching', True):\n _cache_id(newid, id_cache)\n is_ipv4 = salt.utils.network.is_ipv4(newid)\n return newid, is_ipv4\n",
"def _adjust_log_file_override(overrides, default_log_file):\n '''\n Adjusts the log_file based on the log_dir override\n '''\n if overrides.get('log_dir'):\n # Adjust log_file if a log_dir override is introduced\n if overrides.get('log_file'):\n if not os.path.isabs(overrides['log_file']):\n # Prepend log_dir if log_file is relative\n overrides['log_file'] = os.path.join(overrides['log_dir'],\n overrides['log_file'])\n else:\n # Create the log_file override\n overrides['log_file'] = \\\n os.path.join(overrides['log_dir'],\n os.path.basename(default_log_file))\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
client_config
|
python
|
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
|
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L4092-L4171
|
[
"def ip_bracket(addr):\n '''\n Convert IP address representation to ZMQ (URL) format. ZMQ expects\n brackets around IPv6 literals, since they are used in URLs.\n '''\n addr = ipaddress.ip_address(addr)\n return ('[{}]' if addr.version == 6 else '{}').format(addr)\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 master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):\n '''\n Reads in the master configuration file and sets up default options\n\n This is useful for running the actual master daemon. For running\n Master-side client interfaces that need the master opts see\n :py:func:`salt.client.client_config`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n if not os.environ.get(env_var, None):\n # No valid setting was given using the configuration variable.\n # Lets see is SALT_CONFIG_DIR is of any use\n salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)\n if salt_config_dir:\n env_config_file_path = os.path.join(salt_config_dir, 'master')\n if salt_config_dir and os.path.isfile(env_config_file_path):\n # We can get a configuration file using SALT_CONFIG_DIR, let's\n # update the environment with this information\n os.environ[env_var] = env_config_file_path\n\n overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])\n default_include = overrides.get('default_include',\n defaults['default_include'])\n include = overrides.get('include', [])\n\n overrides.update(include_config(default_include, path, verbose=False,\n exit_on_config_errors=exit_on_config_errors))\n overrides.update(include_config(include, path, verbose=True,\n exit_on_config_errors=exit_on_config_errors))\n opts = apply_master_config(overrides, defaults)\n _validate_ssh_minion_opts(opts)\n _validate_opts(opts)\n # If 'nodegroups:' is uncommented in the master config file, and there are\n # no nodegroups defined, opts['nodegroups'] will be None. Fix this by\n # reverting this value to the default, as if 'nodegroups:' was commented\n # out or not present.\n if opts.get('nodegroups') is None:\n opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})\n if salt.utils.data.is_dictlist(opts['nodegroups']):\n opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])\n apply_sdb(opts)\n return opts\n",
"def _validate_opts(opts):\n '''\n Check that all of the types of values passed into the config are\n of the right types\n '''\n def format_multi_opt(valid_type):\n try:\n num_types = len(valid_type)\n except TypeError:\n # Bare type name won't have a length, return the name of the type\n # passed.\n return valid_type.__name__\n else:\n def get_types(types, type_tuple):\n for item in type_tuple:\n if isinstance(item, tuple):\n get_types(types, item)\n else:\n try:\n types.append(item.__name__)\n except AttributeError:\n log.warning(\n 'Unable to interpret type %s while validating '\n 'configuration', item\n )\n types = []\n get_types(types, valid_type)\n\n ret = ', '.join(types[:-1])\n ret += ' or ' + types[-1]\n return ret\n\n errors = []\n\n err = (\n 'Config option \\'{0}\\' with value {1} has an invalid type of {2}, a '\n '{3} is required for this option'\n )\n for key, val in six.iteritems(opts):\n if key in VALID_OPTS:\n if val is None:\n if VALID_OPTS[key] is None:\n continue\n else:\n try:\n if None in VALID_OPTS[key]:\n continue\n except TypeError:\n # VALID_OPTS[key] is not iterable and not None\n pass\n\n if isinstance(val, VALID_OPTS[key]):\n continue\n\n # We don't know what data type sdb will return at run-time so we\n # simply cannot check it for correctness here at start-time.\n if isinstance(val, six.string_types) and val.startswith('sdb://'):\n continue\n\n if hasattr(VALID_OPTS[key], '__call__'):\n try:\n VALID_OPTS[key](val)\n if isinstance(val, (list, dict)):\n # We'll only get here if VALID_OPTS[key] is str or\n # bool, and the passed value is a list/dict. Attempting\n # to run int() or float() on a list/dict will raise an\n # exception, but running str() or bool() on it will\n # pass despite not being the correct type.\n errors.append(\n err.format(\n key,\n val,\n type(val).__name__,\n VALID_OPTS[key].__name__\n )\n )\n except (TypeError, ValueError):\n errors.append(\n err.format(key,\n val,\n type(val).__name__,\n VALID_OPTS[key].__name__)\n )\n continue\n\n errors.append(\n err.format(key,\n val,\n type(val).__name__,\n format_multi_opt(VALID_OPTS[key]))\n )\n\n # Convert list to comma-delimited string for 'return' config option\n if isinstance(opts.get('return'), list):\n opts['return'] = ','.join(opts['return'])\n\n for error in errors:\n log.warning(error)\n if errors:\n return False\n return True\n",
"def load_config(path, env_var, default_path=None, exit_on_config_errors=True):\n '''\n Returns configuration dict from parsing either the file described by\n ``path`` or the environment variable described by ``env_var`` as YAML.\n '''\n if path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if default_path is None:\n # This is most likely not being used from salt, i.e., could be salt-cloud\n # or salt-api which have not yet migrated to the new default_path\n # argument. Let's issue a warning message that the environ vars won't\n # work.\n import inspect\n previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)\n log.warning(\n \"The function '%s()' defined in '%s' is not yet using the \"\n \"new 'default_path' argument to `salt.config.load_config()`. \"\n \"As such, the '%s' environment variable will be ignored\",\n previous_frame.function, previous_frame.filename, env_var\n )\n # In this case, maintain old behavior\n default_path = DEFAULT_MASTER_OPTS['conf_file']\n\n # Default to the environment variable path, if it exists\n env_path = os.environ.get(env_var, path)\n if not env_path or not os.path.isfile(env_path):\n env_path = path\n # If non-default path from `-c`, use that over the env variable\n if path != default_path:\n env_path = path\n\n path = env_path\n\n # If the configuration file is missing, attempt to copy the template,\n # after removing the first header line.\n if not os.path.isfile(path):\n template = '{0}.template'.format(path)\n if os.path.isfile(template):\n log.debug('Writing %s based on %s', path, template)\n with salt.utils.files.fopen(path, 'w') as out:\n with salt.utils.files.fopen(template, 'r') as ifile:\n ifile.readline() # skip first line\n out.write(ifile.read())\n\n opts = {}\n\n if salt.utils.validate.path.is_readable(path):\n try:\n opts = _read_conf_file(path)\n opts['conf_file'] = path\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n log.debug('Missing configuration file: %s', path)\n\n return opts\n",
"def xdg_config_dir():\n '''\n Check xdg locations for config files\n '''\n xdg_config = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))\n xdg_config_directory = os.path.join(xdg_config, 'salt')\n return xdg_config_directory\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
api_config
|
python
|
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
|
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L4174-L4197
|
[
"def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):\n '''\n Load Master configuration data\n\n Usage:\n\n .. code-block:: python\n\n import salt.config\n master_opts = salt.config.client_config('/etc/salt/master')\n\n Returns a dictionary of the Salt Master configuration file with necessary\n options needed to communicate with a locally-running Salt Master daemon.\n This function searches for client specific configurations and adds them to\n the data from the master configuration.\n\n This is useful for master-side operations like\n :py:class:`~salt.client.LocalClient`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n xdg_dir = salt.utils.xdg.xdg_config_dir()\n if os.path.isdir(xdg_dir):\n client_config_dir = xdg_dir\n saltrc_config_file = 'saltrc'\n else:\n client_config_dir = os.path.expanduser('~')\n saltrc_config_file = '.saltrc'\n\n # Get the token file path from the provided defaults. If not found, specify\n # our own, sane, default\n opts = {\n 'token_file': defaults.get(\n 'token_file',\n os.path.join(client_config_dir, 'salt_token')\n )\n }\n # Update options with the master configuration, either from the provided\n # path, salt's defaults or provided defaults\n opts.update(\n master_config(path, defaults=defaults)\n )\n # Update with the users salt dot file or with the environment variable\n saltrc_config = os.path.join(client_config_dir, saltrc_config_file)\n opts.update(\n load_config(\n saltrc_config,\n env_var,\n saltrc_config\n )\n )\n # Make sure we have a proper and absolute path to the token file\n if 'token_file' in opts:\n opts['token_file'] = os.path.abspath(\n os.path.expanduser(\n opts['token_file']\n )\n )\n # If the token file exists, read and store the contained token\n if os.path.isfile(opts['token_file']):\n # Make sure token is still valid\n expire = opts.get('token_expire', 43200)\n if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):\n with salt.utils.files.fopen(opts['token_file']) as fp_:\n opts['token'] = fp_.read().strip()\n # On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost\n if opts['interface'] == '0.0.0.0':\n opts['interface'] = '127.0.0.1'\n\n # Make sure the master_uri is set\n if 'master_uri' not in opts:\n opts['master_uri'] = 'tcp://{ip}:{port}'.format(\n ip=salt.utils.zeromq.ip_bracket(opts['interface']),\n port=opts['ret_port']\n )\n\n # Return the client options\n _validate_opts(opts)\n return opts\n",
"def prepend_root_dir(opts, path_options):\n '''\n Prepends the options that represent filesystem paths with value of the\n 'root_dir' option.\n '''\n root_dir = os.path.abspath(opts['root_dir'])\n def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)\n for path_option in path_options:\n if path_option in opts:\n path = opts[path_option]\n tmp_path_def_root_dir = None\n tmp_path_root_dir = None\n # When running testsuite, salt.syspaths.ROOT_DIR is often empty\n if path == def_root_dir or path.startswith(def_root_dir + os.sep):\n # Remove the default root dir prefix\n tmp_path_def_root_dir = path[len(def_root_dir):]\n if root_dir and (path == root_dir or\n path.startswith(root_dir + os.sep)):\n # Remove the root dir prefix\n tmp_path_root_dir = path[len(root_dir):]\n if tmp_path_def_root_dir and not tmp_path_root_dir:\n # Just the default root dir matched\n path = tmp_path_def_root_dir\n elif tmp_path_root_dir and not tmp_path_def_root_dir:\n # Just the root dir matched\n path = tmp_path_root_dir\n elif tmp_path_def_root_dir and tmp_path_root_dir:\n # In this case both the default root dir and the override root\n # dir matched; this means that either\n # def_root_dir is a substring of root_dir or vice versa\n # We must choose the most specific path\n if def_root_dir in root_dir:\n path = tmp_path_root_dir\n else:\n path = tmp_path_def_root_dir\n elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:\n # In windows, os.path.isabs resolves '/' to 'C:\\\\' or whatever\n # the root drive is. This elif prevents the next from being\n # hit, so that the root_dir is prefixed in cases where the\n # drive is not prefixed on a config option\n pass\n elif os.path.isabs(path):\n # Absolute path (not default or overridden root_dir)\n # No prepending required\n continue\n # Prepending the root dir\n opts[path_option] = salt.utils.path.join(root_dir, path)\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
spm_config
|
python
|
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
|
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L4200-L4221
|
[
"def include_config(include, orig_path, verbose, exit_on_config_errors=False):\n '''\n Parses extra configuration file(s) specified in an include list in the\n main config file.\n '''\n # Protect against empty option\n if not include:\n return {}\n\n if orig_path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if isinstance(include, six.string_types):\n include = [include]\n\n configuration = {}\n for path in include:\n # Allow for includes like ~/foo\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n path = os.path.join(os.path.dirname(orig_path), path)\n\n # Catch situation where user typos path in configuration; also warns\n # for empty include directory (which might be by design)\n glob_matches = glob.glob(path)\n if not glob_matches:\n if verbose:\n log.warning(\n 'Warning parsing configuration file: \"include\" path/glob '\n \"'%s' matches no files\", path\n )\n\n for fn_ in sorted(glob_matches):\n log.debug('Including configuration from \\'%s\\'', fn_)\n try:\n opts = _read_conf_file(fn_)\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n # Initialize default config if we wish to skip config errors\n opts = {}\n schedule = opts.get('schedule', {})\n if schedule and 'schedule' in configuration:\n configuration['schedule'].update(schedule)\n include = opts.get('include', [])\n if include:\n opts.update(include_config(include, fn_, verbose))\n\n salt.utils.dictupdate.update(configuration, opts, True, True)\n\n return configuration\n",
"def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):\n '''\n Load Master configuration data\n\n Usage:\n\n .. code-block:: python\n\n import salt.config\n master_opts = salt.config.client_config('/etc/salt/master')\n\n Returns a dictionary of the Salt Master configuration file with necessary\n options needed to communicate with a locally-running Salt Master daemon.\n This function searches for client specific configurations and adds them to\n the data from the master configuration.\n\n This is useful for master-side operations like\n :py:class:`~salt.client.LocalClient`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n xdg_dir = salt.utils.xdg.xdg_config_dir()\n if os.path.isdir(xdg_dir):\n client_config_dir = xdg_dir\n saltrc_config_file = 'saltrc'\n else:\n client_config_dir = os.path.expanduser('~')\n saltrc_config_file = '.saltrc'\n\n # Get the token file path from the provided defaults. If not found, specify\n # our own, sane, default\n opts = {\n 'token_file': defaults.get(\n 'token_file',\n os.path.join(client_config_dir, 'salt_token')\n )\n }\n # Update options with the master configuration, either from the provided\n # path, salt's defaults or provided defaults\n opts.update(\n master_config(path, defaults=defaults)\n )\n # Update with the users salt dot file or with the environment variable\n saltrc_config = os.path.join(client_config_dir, saltrc_config_file)\n opts.update(\n load_config(\n saltrc_config,\n env_var,\n saltrc_config\n )\n )\n # Make sure we have a proper and absolute path to the token file\n if 'token_file' in opts:\n opts['token_file'] = os.path.abspath(\n os.path.expanduser(\n opts['token_file']\n )\n )\n # If the token file exists, read and store the contained token\n if os.path.isfile(opts['token_file']):\n # Make sure token is still valid\n expire = opts.get('token_expire', 43200)\n if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):\n with salt.utils.files.fopen(opts['token_file']) as fp_:\n opts['token'] = fp_.read().strip()\n # On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost\n if opts['interface'] == '0.0.0.0':\n opts['interface'] = '127.0.0.1'\n\n # Make sure the master_uri is set\n if 'master_uri' not in opts:\n opts['master_uri'] = 'tcp://{ip}:{port}'.format(\n ip=salt.utils.zeromq.ip_bracket(opts['interface']),\n port=opts['ret_port']\n )\n\n # Return the client options\n _validate_opts(opts)\n return opts\n",
"def load_config(path, env_var, default_path=None, exit_on_config_errors=True):\n '''\n Returns configuration dict from parsing either the file described by\n ``path`` or the environment variable described by ``env_var`` as YAML.\n '''\n if path is None:\n # When the passed path is None, we just want the configuration\n # defaults, not actually loading the whole configuration.\n return {}\n\n if default_path is None:\n # This is most likely not being used from salt, i.e., could be salt-cloud\n # or salt-api which have not yet migrated to the new default_path\n # argument. Let's issue a warning message that the environ vars won't\n # work.\n import inspect\n previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)\n log.warning(\n \"The function '%s()' defined in '%s' is not yet using the \"\n \"new 'default_path' argument to `salt.config.load_config()`. \"\n \"As such, the '%s' environment variable will be ignored\",\n previous_frame.function, previous_frame.filename, env_var\n )\n # In this case, maintain old behavior\n default_path = DEFAULT_MASTER_OPTS['conf_file']\n\n # Default to the environment variable path, if it exists\n env_path = os.environ.get(env_var, path)\n if not env_path or not os.path.isfile(env_path):\n env_path = path\n # If non-default path from `-c`, use that over the env variable\n if path != default_path:\n env_path = path\n\n path = env_path\n\n # If the configuration file is missing, attempt to copy the template,\n # after removing the first header line.\n if not os.path.isfile(path):\n template = '{0}.template'.format(path)\n if os.path.isfile(template):\n log.debug('Writing %s based on %s', path, template)\n with salt.utils.files.fopen(path, 'w') as out:\n with salt.utils.files.fopen(template, 'r') as ifile:\n ifile.readline() # skip first line\n out.write(ifile.read())\n\n opts = {}\n\n if salt.utils.validate.path.is_readable(path):\n try:\n opts = _read_conf_file(path)\n opts['conf_file'] = path\n except salt.exceptions.SaltConfigurationError as error:\n log.error(error)\n if exit_on_config_errors:\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\n else:\n log.debug('Missing configuration file: %s', path)\n\n return opts\n",
"def apply_master_config(overrides=None, defaults=None):\n '''\n Returns master configurations dict.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n if overrides is None:\n overrides = {}\n\n opts = defaults.copy()\n opts['__role'] = 'master'\n _adjust_log_file_override(overrides, defaults['log_file'])\n if overrides:\n opts.update(overrides)\n\n opts['__cli'] = salt.utils.stringutils.to_unicode(\n os.path.basename(sys.argv[0])\n )\n\n if 'environment' in opts:\n if opts['saltenv'] is not None:\n log.warning(\n 'The \\'saltenv\\' and \\'environment\\' master config options '\n 'cannot both be used. Ignoring \\'environment\\' in favor of '\n '\\'saltenv\\'.',\n )\n # Set environment to saltenv in case someone's custom runner is\n # refrencing __opts__['environment']\n opts['environment'] = opts['saltenv']\n else:\n log.warning(\n 'The \\'environment\\' master config option has been renamed '\n 'to \\'saltenv\\'. Using %s as the \\'saltenv\\' config value.',\n opts['environment']\n )\n opts['saltenv'] = opts['environment']\n\n if six.PY2 and 'rest_cherrypy' in opts:\n # CherryPy is not unicode-compatible\n opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])\n\n for idx, val in enumerate(opts['fileserver_backend']):\n if val in ('git', 'hg', 'svn', 'minion'):\n new_val = val + 'fs'\n log.debug(\n 'Changed %s to %s in master opts\\' fileserver_backend list',\n val, new_val\n )\n opts['fileserver_backend'][idx] = new_val\n\n if len(opts['sock_dir']) > len(opts['cachedir']) + 10:\n opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')\n\n opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')\n opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')\n # Make sure ext_mods gets set if it is an untrue value\n # (here to catch older bad configs)\n opts['extension_modules'] = (\n opts.get('extension_modules') or\n os.path.join(opts['cachedir'], 'extmods')\n )\n # Set up the utils_dirs location from the extension_modules location\n opts['utils_dirs'] = (\n opts.get('utils_dirs') or\n [os.path.join(opts['extension_modules'], 'utils')]\n )\n\n # Insert all 'utils_dirs' directories to the system path\n insert_system_path(opts, opts['utils_dirs'])\n\n if overrides.get('ipc_write_buffer', '') == 'dynamic':\n opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER\n\n using_ip_for_id = False\n append_master = False\n if not opts.get('id'):\n opts['id'], using_ip_for_id = get_id(\n opts,\n cache_minion_id=None)\n append_master = True\n\n # it does not make sense to append a domain to an IP based id\n if not using_ip_for_id and 'append_domain' in opts:\n opts['id'] = _append_domain(opts)\n if append_master:\n opts['id'] += '_master'\n\n # Prepend root_dir to other paths\n prepend_root_dirs = [\n 'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',\n 'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',\n 'sqlite_queue_dir', 'autosign_grains_dir'\n ]\n\n # These can be set to syslog, so, not actual paths on the system\n for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):\n log_setting = opts.get(config_key, '')\n if log_setting is None:\n continue\n\n if urlparse(log_setting).scheme == '':\n prepend_root_dirs.append(config_key)\n\n prepend_root_dir(opts, prepend_root_dirs)\n\n # Enabling open mode requires that the value be set to True, and\n # nothing else!\n opts['open_mode'] = opts['open_mode'] is True\n opts['auto_accept'] = opts['auto_accept'] is True\n opts['file_roots'] = _validate_file_roots(opts['file_roots'])\n opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])\n\n if opts['file_ignore_regex']:\n # If file_ignore_regex was given, make sure it's wrapped in a list.\n # Only keep valid regex entries for improved performance later on.\n if isinstance(opts['file_ignore_regex'], six.string_types):\n ignore_regex = [opts['file_ignore_regex']]\n elif isinstance(opts['file_ignore_regex'], list):\n ignore_regex = opts['file_ignore_regex']\n\n opts['file_ignore_regex'] = []\n for regex in ignore_regex:\n try:\n # Can't store compiled regex itself in opts (breaks\n # serialization)\n re.compile(regex)\n opts['file_ignore_regex'].append(regex)\n except Exception:\n log.warning(\n 'Unable to parse file_ignore_regex. Skipping: %s',\n regex\n )\n\n if opts['file_ignore_glob']:\n # If file_ignore_glob was given, make sure it's wrapped in a list.\n if isinstance(opts['file_ignore_glob'], six.string_types):\n opts['file_ignore_glob'] = [opts['file_ignore_glob']]\n\n # Let's make sure `worker_threads` does not drop below 3 which has proven\n # to make `salt.modules.publish` not work under the test-suite.\n if opts['worker_threads'] < 3 and opts.get('peer', None):\n log.warning(\n \"The 'worker_threads' setting in '%s' cannot be lower than \"\n '3. Resetting it to the default value of 3.', opts['conf_file']\n )\n opts['worker_threads'] = 3\n\n opts.setdefault('pillar_source_merging_strategy', 'smart')\n\n # Make sure hash_type is lowercase\n opts['hash_type'] = opts['hash_type'].lower()\n\n # Check and update TLS/SSL configuration\n _update_ssl_config(opts)\n _update_discovery_config(opts)\n\n return opts\n",
"def apply_spm_config(overrides, defaults):\n '''\n Returns the spm configurations dict.\n\n .. versionadded:: 2015.8.1\n '''\n opts = defaults.copy()\n _adjust_log_file_override(overrides, defaults['log_file'])\n if overrides:\n opts.update(overrides)\n\n # Prepend root_dir to other paths\n prepend_root_dirs = [\n 'formula_path', 'pillar_path', 'reactor_path',\n 'spm_cache_dir', 'spm_build_dir'\n ]\n\n # These can be set to syslog, so, not actual paths on the system\n for config_key in ('spm_logfile',):\n log_setting = opts.get(config_key, '')\n if log_setting is None:\n continue\n\n if urlparse(log_setting).scheme == '':\n prepend_root_dirs.append(config_key)\n\n prepend_root_dir(opts, prepend_root_dirs)\n return opts\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
saltstack/salt
|
salt/config/__init__.py
|
apply_spm_config
|
python
|
def apply_spm_config(overrides, defaults):
'''
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
'''
opts = defaults.copy()
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
# Prepend root_dir to other paths
prepend_root_dirs = [
'formula_path', 'pillar_path', 'reactor_path',
'spm_cache_dir', 'spm_build_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('spm_logfile',):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
|
Returns the spm configurations dict.
.. versionadded:: 2015.8.1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/config/__init__.py#L4224-L4251
|
[
"def prepend_root_dir(opts, path_options):\n '''\n Prepends the options that represent filesystem paths with value of the\n 'root_dir' option.\n '''\n root_dir = os.path.abspath(opts['root_dir'])\n def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)\n for path_option in path_options:\n if path_option in opts:\n path = opts[path_option]\n tmp_path_def_root_dir = None\n tmp_path_root_dir = None\n # When running testsuite, salt.syspaths.ROOT_DIR is often empty\n if path == def_root_dir or path.startswith(def_root_dir + os.sep):\n # Remove the default root dir prefix\n tmp_path_def_root_dir = path[len(def_root_dir):]\n if root_dir and (path == root_dir or\n path.startswith(root_dir + os.sep)):\n # Remove the root dir prefix\n tmp_path_root_dir = path[len(root_dir):]\n if tmp_path_def_root_dir and not tmp_path_root_dir:\n # Just the default root dir matched\n path = tmp_path_def_root_dir\n elif tmp_path_root_dir and not tmp_path_def_root_dir:\n # Just the root dir matched\n path = tmp_path_root_dir\n elif tmp_path_def_root_dir and tmp_path_root_dir:\n # In this case both the default root dir and the override root\n # dir matched; this means that either\n # def_root_dir is a substring of root_dir or vice versa\n # We must choose the most specific path\n if def_root_dir in root_dir:\n path = tmp_path_root_dir\n else:\n path = tmp_path_def_root_dir\n elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:\n # In windows, os.path.isabs resolves '/' to 'C:\\\\' or whatever\n # the root drive is. This elif prevents the next from being\n # hit, so that the root_dir is prefixed in cases where the\n # drive is not prefixed on a config option\n pass\n elif os.path.isabs(path):\n # Absolute path (not default or overridden root_dir)\n # No prepending required\n continue\n # Prepending the root dir\n opts[path_option] = salt.utils.path.join(root_dir, path)\n",
"def _adjust_log_file_override(overrides, default_log_file):\n '''\n Adjusts the log_file based on the log_dir override\n '''\n if overrides.get('log_dir'):\n # Adjust log_file if a log_dir override is introduced\n if overrides.get('log_file'):\n if not os.path.isabs(overrides['log_file']):\n # Prepend log_dir if log_file is relative\n overrides['log_file'] = os.path.join(overrides['log_dir'],\n overrides['log_file'])\n else:\n # Create the log_file override\n overrides['log_file'] = \\\n os.path.join(overrides['log_dir'],\n os.path.basename(default_log_file))\n"
] |
# -*- coding: utf-8 -*-
'''
All salt configuration loading and defaults should be in this module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals, generators
import os
import re
import sys
import glob
import time
import codecs
import logging
import types
from copy import deepcopy
# pylint: disable=import-error,no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse
# pylint: enable=import-error,no-name-in-module
# Import salt libs
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.user
import salt.utils.validate.path
import salt.utils.xdg
import salt.utils.yaml
import salt.utils.zeromq
import salt.syspaths
import salt.exceptions
import salt.defaults.exitcodes
import salt.utils.immutabletypes as immutabletypes
try:
import psutil
if not hasattr(psutil, 'virtual_memory'):
raise ImportError('Version of psutil too old.')
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
log = logging.getLogger(__name__)
_DFLT_LOG_DATEFMT = '%H:%M:%S'
_DFLT_LOG_DATEFMT_LOGFILE = '%Y-%m-%d %H:%M:%S'
_DFLT_LOG_FMT_CONSOLE = '[%(levelname)-8s] %(message)s'
_DFLT_LOG_FMT_LOGFILE = (
'%(asctime)s,%(msecs)03d [%(name)-17s:%(lineno)-4d][%(levelname)-8s][%(process)d] %(message)s'
)
_DFLT_LOG_FMT_JID = "[JID: %(jid)s]"
_DFLT_REFSPECS = ['+refs/heads/*:refs/remotes/origin/*', '+refs/tags/*:refs/tags/*']
DEFAULT_INTERVAL = 60
if salt.utils.platform.is_windows():
# Since an 'ipc_mode' of 'ipc' will never work on Windows due to lack of
# support in ZeroMQ, we want the default to be something that has a
# chance of working.
_DFLT_IPC_MODE = 'tcp'
_MASTER_TRIES = -1
# This needs to be SYSTEM in order for salt-master to run as a Service
# Otherwise, it will not respond to CLI calls
_MASTER_USER = 'SYSTEM'
else:
_DFLT_IPC_MODE = 'ipc'
_MASTER_TRIES = 1
_MASTER_USER = salt.utils.user.get_user()
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid loading core grains unless absolutely required
import platform
import salt.grains.core
# We need to load up ``mem_total`` grain. Let's mimic required OS data.
os_data = {'kernel': platform.system()}
grains = salt.grains.core._memdata(os_data)
total_mem = grains['mem_total'] * 1024 * 1024
# Return the higher number between 5% of the system memory and 10MiB
return max([total_mem * 0.05, 10 << 20])
# For the time being this will be a fixed calculation
# TODO: Allow user configuration
_DFLT_IPC_WBUFFER = _gather_buffer_space() * .5
# TODO: Reserved for future use
_DFLT_IPC_RBUFFER = _gather_buffer_space() * .5
VALID_OPTS = immutabletypes.freeze({
# The address of the salt master. May be specified as IP address or hostname
'master': (six.string_types, list),
# The TCP/UDP port of the master to connect to in order to listen to publications
'master_port': (six.string_types, int),
# The behaviour of the minion when connecting to a master. Can specify 'failover',
# 'disable', 'distributed', or 'func'. If 'func' is specified, the 'master' option should be
# set to an exec module function to run to determine the master hostname. If 'disable' is
# specified the minion will run, but will not try to connect to a master. If 'distributed'
# is specified the minion will try to deterministically pick a master based on its' id.
'master_type': six.string_types,
# Specify the format in which the master address will be specified. Can
# specify 'default' or 'ip_only'. If 'ip_only' is specified, then the
# master address will not be split into IP and PORT.
'master_uri_format': six.string_types,
# The following optiosn refer to the Minion only, and they specify
# the details of the source address / port to be used when connecting to
# the Master. This is useful when dealing withmachines where due to firewall
# rules you are restricted to use a certain IP/port combination only.
'source_interface_name': six.string_types,
'source_address': six.string_types,
'source_ret_port': (six.string_types, int),
'source_publish_port': (six.string_types, int),
# The fingerprint of the master key may be specified to increase security. Generate
# a master fingerprint with `salt-key -F master`
'master_finger': six.string_types,
# Deprecated in 2019.2.0. Use 'random_master' instead.
# Do not remove! Keep as an alias for usability.
'master_shuffle': bool,
# When in multi-master mode, temporarily remove a master from the list if a conenction
# is interrupted and try another master in the list.
'master_alive_interval': int,
# When in multi-master failover mode, fail back to the first master in the list if it's back
# online.
'master_failback': bool,
# When in multi-master mode, and master_failback is enabled ping the top master with this
# interval.
'master_failback_interval': int,
# The name of the signing key-pair
'master_sign_key_name': six.string_types,
# Sign the master auth-replies with a cryptographic signature of the masters public key.
'master_sign_pubkey': bool,
# Enables verification of the master-public-signature returned by the master in auth-replies.
# Must also set master_sign_pubkey for this to work
'verify_master_pubkey_sign': bool,
# If verify_master_pubkey_sign is enabled, the signature is only verified, if the public-key of
# the master changes. If the signature should always be verified, this can be set to True.
'always_verify_signature': bool,
# The name of the file in the masters pki-directory that holds the pre-calculated signature of
# the masters public-key
'master_pubkey_signature': six.string_types,
# Instead of computing the signature for each auth-reply, use a pre-calculated signature.
# The master_pubkey_signature must also be set for this.
'master_use_pubkey_signature': bool,
# Enable master stats eveents to be fired, these events will contain information about
# what commands the master is processing and what the rates are of the executions
'master_stats': bool,
'master_stats_event_iter': int,
# The key fingerprint of the higher-level master for the syndic to verify it is talking to the
# intended master
'syndic_finger': six.string_types,
# The caching mechanism to use for the PKI key store. Can substantially decrease master publish
# times. Available types:
# 'maint': Runs on a schedule as a part of the maintanence process.
# '': Disable the key cache [default]
'key_cache': six.string_types,
# The user under which the daemon should run
'user': six.string_types,
# The root directory prepended to these options: pki_dir, cachedir,
# sock_dir, log_file, autosign_file, autoreject_file, extension_modules,
# key_logfile, pidfile:
'root_dir': six.string_types,
# The directory used to store public key data
'pki_dir': six.string_types,
# A unique identifier for this daemon
'id': six.string_types,
# Use a module function to determine the unique identifier. If this is
# set and 'id' is not set, it will allow invocation of a module function
# to determine the value of 'id'. For simple invocations without function
# arguments, this may be a string that is the function name. For
# invocations with function arguments, this may be a dictionary with the
# key being the function name, and the value being an embedded dictionary
# where each key is a function argument name and each value is the
# corresponding argument value.
'id_function': (dict, six.string_types),
# The directory to store all cache files.
'cachedir': six.string_types,
# Append minion_id to these directories. Helps with
# multiple proxies and minions running on the same machine.
# Allowed elements in the list: pki_dir, cachedir, extension_modules, pidfile
'append_minionid_config_dirs': list,
# Flag to cache jobs locally.
'cache_jobs': bool,
# The path to the salt configuration file
'conf_file': six.string_types,
# The directory containing unix sockets for things like the event bus
'sock_dir': six.string_types,
# The pool size of unix sockets, it is necessary to avoid blocking waiting for zeromq and tcp communications.
'sock_pool_size': int,
# Specifies how the file server should backup files, if enabled. The backups
# live in the cache dir.
'backup_mode': six.string_types,
# A default renderer for all operations on this host
'renderer': six.string_types,
# Renderer whitelist. The only renderers from this list are allowed.
'renderer_whitelist': list,
# Rendrerer blacklist. Renderers from this list are disalloed even if specified in whitelist.
'renderer_blacklist': list,
# A flag indicating that a highstate run should immediately cease if a failure occurs.
'failhard': bool,
# A flag to indicate that highstate runs should force refresh the modules prior to execution
'autoload_dynamic_modules': bool,
# Force the minion into a single environment when it fetches files from the master
'saltenv': (type(None), six.string_types),
# Prevent saltenv from being overridden on the command line
'lock_saltenv': bool,
# Force the minion into a single pillar root when it fetches pillar data from the master
'pillarenv': (type(None), six.string_types),
# Make the pillarenv always match the effective saltenv
'pillarenv_from_saltenv': bool,
# Allows a user to provide an alternate name for top.sls
'state_top': six.string_types,
'state_top_saltenv': (type(None), six.string_types),
# States to run when a minion starts up
'startup_states': six.string_types,
# List of startup states
'sls_list': list,
# Configuration for snapper in the state system
'snapper_states': bool,
'snapper_states_config': six.string_types,
# A top file to execute if startup_states == 'top'
'top_file': six.string_types,
# Location of the files a minion should look for. Set to 'local' to never ask the master.
'file_client': six.string_types,
'local': bool,
# When using a local file_client, this parameter is used to allow the client to connect to
# a master for remote execution.
'use_master_when_local': bool,
# A map of saltenvs and fileserver backend locations
'file_roots': dict,
# A map of saltenvs and fileserver backend locations
'pillar_roots': dict,
# The external pillars permitted to be used on-demand using pillar.ext
'on_demand_ext_pillar': list,
# A map of glob paths to be used
'decrypt_pillar': list,
# Delimiter to use in path expressions for decrypt_pillar
'decrypt_pillar_delimiter': six.string_types,
# Default renderer for decrypt_pillar
'decrypt_pillar_default': six.string_types,
# List of renderers available for decrypt_pillar
'decrypt_pillar_renderers': list,
# The type of hashing algorithm to use when doing file comparisons
'hash_type': six.string_types,
# Order of preference for optimized .pyc files (PY3 only)
'optimization_order': list,
# Refuse to load these modules
'disable_modules': list,
# Refuse to load these returners
'disable_returners': list,
# Tell the loader to only load modules in this list
'whitelist_modules': list,
# A list of additional directories to search for salt modules in
'module_dirs': list,
# A list of additional directories to search for salt returners in
'returner_dirs': list,
# A list of additional directories to search for salt states in
'states_dirs': list,
# A list of additional directories to search for salt grains in
'grains_dirs': list,
# A list of additional directories to search for salt renderers in
'render_dirs': list,
# A list of additional directories to search for salt outputters in
'outputter_dirs': list,
# A list of additional directories to search for salt utilities in. (Used by the loader
# to populate __utils__)
'utils_dirs': list,
# salt cloud providers
'providers': dict,
# First remove all modules during any sync operation
'clean_dynamic_modules': bool,
# A flag indicating that a master should accept any minion connection without any authentication
'open_mode': bool,
# Whether or not processes should be forked when needed. The alternative is to use threading.
'multiprocessing': bool,
# Maximum number of concurrently active processes at any given point in time
'process_count_max': int,
# If the minion reaches process_count_max, how long should it sleep
# before trying to generate a new process.
'process_count_max_sleep_secs': int,
# Whether or not the salt minion should run scheduled mine updates
'mine_enabled': bool,
# Whether or not scheduled mine updates should be accompanied by a job return for the job cache
'mine_return_job': bool,
# The number of minutes between mine updates.
'mine_interval': int,
# The ipc strategy. (i.e., sockets versus tcp, etc)
'ipc_mode': six.string_types,
# Enable ipv6 support for daemons
'ipv6': (type(None), bool),
# The chunk size to use when streaming files with the file server
'file_buffer_size': int,
# The TCP port on which minion events should be published if ipc_mode is TCP
'tcp_pub_port': int,
# The TCP port on which minion events should be pulled if ipc_mode is TCP
'tcp_pull_port': int,
# The TCP port on which events for the master should be published if ipc_mode is TCP
'tcp_master_pub_port': int,
# The TCP port on which events for the master should be pulled if ipc_mode is TCP
'tcp_master_pull_port': int,
# The TCP port on which events for the master should pulled and then republished onto
# the event bus on the master
'tcp_master_publish_pull': int,
# The TCP port for mworkers to connect to on the master
'tcp_master_workers': int,
# The file to send logging data to
'log_file': six.string_types,
# The level of verbosity at which to log
'log_level': six.string_types,
# The log level to log to a given file
'log_level_logfile': (type(None), six.string_types),
# The format to construct dates in log files
'log_datefmt': six.string_types,
# The dateformat for a given logfile
'log_datefmt_logfile': six.string_types,
# The format for console logs
'log_fmt_console': six.string_types,
# The format for a given log file
'log_fmt_logfile': (tuple, six.string_types),
# A dictionary of logging levels
'log_granular_levels': dict,
# The maximum number of bytes a single log file may contain before
# it is rotated. A value of 0 disables this feature.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_max_bytes': int,
# The number of backup files to keep when rotating log files. Only
# used if log_rotate_max_bytes is greater than 0.
# Currently only supported on Windows. On other platforms, use an
# external tool such as 'logrotate' to manage log files.
'log_rotate_backup_count': int,
# If an event is above this size, it will be trimmed before putting it on the event bus
'max_event_size': int,
# Enable old style events to be sent on minion_startup. Change default to False in Sodium release
'enable_legacy_startup_events': bool,
# Always execute states with test=True if this flag is set
'test': bool,
# Tell the loader to attempt to import *.pyx cython files if cython is available
'cython_enable': bool,
# Whether or not to load grains for the GPU
'enable_gpu_grains': bool,
# Tell the loader to attempt to import *.zip archives
'enable_zip_modules': bool,
# Tell the client to show minions that have timed out
'show_timeout': bool,
# Tell the client to display the jid when a job is published
'show_jid': bool,
# Generate jids based on UTC time instead of local time
'utc_jid': bool,
# Ensure that a generated jid is always unique. If this is set, the jid
# format is different due to an underscore and process id being appended
# to the jid. WARNING: A change to the jid format may break external
# applications that depend on the original format.
'unique_jid': bool,
# Tells the highstate outputter to show successful states. False will omit successes.
'state_verbose': bool,
# Specify the format for state outputs. See highstate outputter for additional details.
'state_output': six.string_types,
# Tells the highstate outputter to only report diffs of states that changed
'state_output_diff': bool,
# When true, states run in the order defined in an SLS file, unless requisites re-order them
'state_auto_order': bool,
# Fire events as state chunks are processed by the state compiler
'state_events': bool,
# The number of seconds a minion should wait before retry when attempting authentication
'acceptance_wait_time': float,
# The number of seconds a minion should wait before giving up during authentication
'acceptance_wait_time_max': float,
# Retry a connection attempt if the master rejects a minion's public key
'rejected_retry': bool,
# The interval in which a daemon's main loop should attempt to perform all necessary tasks
# for normal operation
'loop_interval': float,
# Perform pre-flight verification steps before daemon startup, such as checking configuration
# files and certain directories.
'verify_env': bool,
# The grains dictionary for a minion, containing specific "facts" about the minion
'grains': dict,
# Allow a daemon to function even if the key directories are not secured
'permissive_pki_access': bool,
# The passphrase of the master's private key
'key_pass': (type(None), six.string_types),
# The passphrase of the master's private signing key
'signing_key_pass': (type(None), six.string_types),
# The path to a directory to pull in configuration file includes
'default_include': six.string_types,
# If a minion is running an esky build of salt, upgrades can be performed using the url
# defined here. See saltutil.update() for additional information
'update_url': (bool, six.string_types),
# If using update_url with saltutil.update(), provide a list of services to be restarted
# post-install
'update_restart_services': list,
# The number of seconds to sleep between retrying an attempt to resolve the hostname of a
# salt master
'retry_dns': float,
'retry_dns_count': (type(None), int),
# In the case when the resolve of the salt master hostname fails, fall back to localhost
'resolve_dns_fallback': bool,
# set the zeromq_reconnect_ivl option on the minion.
# http://lists.zeromq.org/pipermail/zeromq-dev/2011-January/008845.html
'recon_max': float,
# If recon_randomize is set, this specifies the lower bound for the randomized period
'recon_default': float,
# Tells the minion to choose a bounded, random interval to have zeromq attempt to reconnect
# in the event of a disconnect event
'recon_randomize': bool,
'return_retry_timer': int,
'return_retry_timer_max': int,
# Specify one or more returners in which all events will be sent to. Requires that the returners
# in question have an event_return(event) function!
'event_return': (list, six.string_types),
# The number of events to queue up in memory before pushing them down the pipe to an event
# returner specified by 'event_return'
'event_return_queue': int,
# Only forward events to an event returner if it matches one of the tags in this list
'event_return_whitelist': list,
# Events matching a tag in this list should never be sent to an event returner.
'event_return_blacklist': list,
# default match type for filtering events tags: startswith, endswith, find, regex, fnmatch
'event_match_type': six.string_types,
# This pidfile to write out to when a daemon starts
'pidfile': six.string_types,
# Used with the SECO range master tops system
'range_server': six.string_types,
# The tcp keepalive interval to set on TCP ports. This setting can be used to tune Salt
# connectivity issues in messy network environments with misbehaving firewalls
'tcp_keepalive': bool,
# Sets zeromq TCP keepalive idle. May be used to tune issues with minion disconnects
'tcp_keepalive_idle': float,
# Sets zeromq TCP keepalive count. May be used to tune issues with minion disconnects
'tcp_keepalive_cnt': float,
# Sets zeromq TCP keepalive interval. May be used to tune issues with minion disconnects.
'tcp_keepalive_intvl': float,
# The network interface for a daemon to bind to
'interface': six.string_types,
# The port for a salt master to broadcast publications on. This will also be the port minions
# connect to to listen for publications.
'publish_port': int,
# TODO unknown option!
'auth_mode': int,
# listen queue size / backlog
'zmq_backlog': int,
# Set the zeromq high water mark on the publisher interface.
# http://api.zeromq.org/3-2:zmq-setsockopt
'pub_hwm': int,
# IPC buffer size
# Refs https://github.com/saltstack/salt/issues/34215
'ipc_write_buffer': int,
# IPC tcp socket max send buffer
'ipc_so_sndbuf': (type(None), int),
# IPC tcp socket max receive buffer
'ipc_so_rcvbuf': (type(None), int),
# IPC tcp socket backlog size
'ipc_so_backlog': (type(None), int),
# The number of MWorker processes for a master to startup. This number needs to scale up as
# the number of connected minions increases.
'worker_threads': int,
# The port for the master to listen to returns on. The minion needs to connect to this port
# to send returns.
'ret_port': int,
# The number of hours to keep jobs around in the job cache on the master
'keep_jobs': int,
# If the returner supports `clean_old_jobs`, then at cleanup time,
# archive the job data before deleting it.
'archive_jobs': bool,
# A master-only copy of the file_roots dictionary, used by the state compiler
'master_roots': dict,
# Add the proxymodule LazyLoader object to opts. This breaks many things
# but this was the default pre 2015.8.2. This should default to
# False in 2016.3.0
'add_proxymodule_to_opts': bool,
# Merge pillar data into configuration opts.
# As multiple proxies can run on the same server, we may need different
# configuration options for each, while there's one single configuration file.
# The solution is merging the pillar data of each proxy minion into the opts.
'proxy_merge_pillar_in_opts': bool,
# Deep merge of pillar data into configuration opts.
# Evaluated only when `proxy_merge_pillar_in_opts` is True.
'proxy_deep_merge_pillar_in_opts': bool,
# The strategy used when merging pillar into opts.
# Considered only when `proxy_merge_pillar_in_opts` is True.
'proxy_merge_pillar_in_opts_strategy': six.string_types,
# Allow enabling mine details using pillar data.
'proxy_mines_pillar': bool,
# In some particular cases, always alive proxies are not beneficial.
# This option can be used in those less dynamic environments:
# the user can request the connection
# always alive, or init-shutdown per command.
'proxy_always_alive': bool,
# Poll the connection state with the proxy minion
# If enabled, this option requires the function `alive`
# to be implemented in the proxy module
'proxy_keep_alive': bool,
# Frequency of the proxy_keep_alive, in minutes
'proxy_keep_alive_interval': int,
# Update intervals
'roots_update_interval': int,
'azurefs_update_interval': int,
'gitfs_update_interval': int,
'hgfs_update_interval': int,
'minionfs_update_interval': int,
's3fs_update_interval': int,
'svnfs_update_interval': int,
# NOTE: git_pillar_base, git_pillar_branch, git_pillar_env, and
# git_pillar_root omitted here because their values could conceivably be
# loaded as non-string types, which is OK because git_pillar will normalize
# them to strings. But rather than include all the possible types they
# could be, we'll just skip type-checking.
'git_pillar_ssl_verify': bool,
'git_pillar_global_lock': bool,
'git_pillar_user': six.string_types,
'git_pillar_password': six.string_types,
'git_pillar_insecure_auth': bool,
'git_pillar_privkey': six.string_types,
'git_pillar_pubkey': six.string_types,
'git_pillar_passphrase': six.string_types,
'git_pillar_refspecs': list,
'git_pillar_includes': bool,
'git_pillar_verify_config': bool,
# NOTE: gitfs_base, gitfs_mountpoint, and gitfs_root omitted here because
# their values could conceivably be loaded as non-string types, which is OK
# because gitfs will normalize them to strings. But rather than include all
# the possible types they could be, we'll just skip type-checking.
'gitfs_remotes': list,
'gitfs_insecure_auth': bool,
'gitfs_privkey': six.string_types,
'gitfs_pubkey': six.string_types,
'gitfs_passphrase': six.string_types,
'gitfs_env_whitelist': list,
'gitfs_env_blacklist': list,
'gitfs_saltenv_whitelist': list,
'gitfs_saltenv_blacklist': list,
'gitfs_ssl_verify': bool,
'gitfs_global_lock': bool,
'gitfs_saltenv': list,
'gitfs_ref_types': list,
'gitfs_refspecs': list,
'gitfs_disable_saltenv_mapping': bool,
'hgfs_remotes': list,
'hgfs_mountpoint': six.string_types,
'hgfs_root': six.string_types,
'hgfs_base': six.string_types,
'hgfs_branch_method': six.string_types,
'hgfs_env_whitelist': list,
'hgfs_env_blacklist': list,
'hgfs_saltenv_whitelist': list,
'hgfs_saltenv_blacklist': list,
'svnfs_remotes': list,
'svnfs_mountpoint': six.string_types,
'svnfs_root': six.string_types,
'svnfs_trunk': six.string_types,
'svnfs_branches': six.string_types,
'svnfs_tags': six.string_types,
'svnfs_env_whitelist': list,
'svnfs_env_blacklist': list,
'svnfs_saltenv_whitelist': list,
'svnfs_saltenv_blacklist': list,
'minionfs_env': six.string_types,
'minionfs_mountpoint': six.string_types,
'minionfs_whitelist': list,
'minionfs_blacklist': list,
# Specify a list of external pillar systems to use
'ext_pillar': list,
# Reserved for future use to version the pillar structure
'pillar_version': int,
# Whether or not a copy of the master opts dict should be rendered into minion pillars
'pillar_opts': bool,
# Cache the master pillar to disk to avoid having to pass through the rendering system
'pillar_cache': bool,
# Pillar cache TTL, in seconds. Has no effect unless `pillar_cache` is True
'pillar_cache_ttl': int,
# Pillar cache backend. Defaults to `disk` which stores caches in the master cache
'pillar_cache_backend': six.string_types,
'pillar_safe_render_error': bool,
# When creating a pillar, there are several strategies to choose from when
# encountering duplicate values
'pillar_source_merging_strategy': six.string_types,
# Recursively merge lists by aggregating them instead of replacing them.
'pillar_merge_lists': bool,
# If True, values from included pillar SLS targets will override
'pillar_includes_override_sls': bool,
# How to merge multiple top files from multiple salt environments
# (saltenvs); can be 'merge' or 'same'
'top_file_merging_strategy': six.string_types,
# The ordering for salt environment merging, when top_file_merging_strategy
# is set to 'same'
'env_order': list,
# The salt environment which provides the default top file when
# top_file_merging_strategy is set to 'same'; defaults to 'base'
'default_top': six.string_types,
'ping_on_rotate': bool,
'peer': dict,
'preserve_minion_cache': bool,
'syndic_master': (six.string_types, list),
# The behaviour of the multimaster syndic when connection to a master of masters failed. Can
# specify 'random' (default) or 'ordered'. If set to 'random' masters will be iterated in random
# order if 'ordered' the configured order will be used.
'syndic_failover': six.string_types,
'syndic_forward_all_events': bool,
'runner_dirs': list,
'client_acl_verify': bool,
'publisher_acl': dict,
'publisher_acl_blacklist': dict,
'sudo_acl': bool,
'external_auth': dict,
'token_expire': int,
'token_expire_user_override': (bool, dict),
'file_recv': bool,
'file_recv_max_size': int,
'file_ignore_regex': (list, six.string_types),
'file_ignore_glob': (list, six.string_types),
'fileserver_backend': list,
'fileserver_followsymlinks': bool,
'fileserver_ignoresymlinks': bool,
'fileserver_limit_traversal': bool,
'fileserver_verify_config': bool,
# Optionally apply '*' permissioins to any user. By default '*' is a fallback case that is
# applied only if the user didn't matched by other matchers.
'permissive_acl': bool,
# Optionally enables keeping the calculated user's auth list in the token file.
'keep_acl_in_token': bool,
# Auth subsystem module to use to get authorized access list for a user. By default it's the
# same module used for external authentication.
'eauth_acl_module': six.string_types,
# Subsystem to use to maintain eauth tokens. By default, tokens are stored on the local
# filesystem
'eauth_tokens': six.string_types,
# The number of open files a daemon is allowed to have open. Frequently needs to be increased
# higher than the system default in order to account for the way zeromq consumes file handles.
'max_open_files': int,
# Automatically accept any key provided to the master. Implies that the key will be preserved
# so that subsequent connections will be authenticated even if this option has later been
# turned off.
'auto_accept': bool,
'autosign_timeout': int,
# A mapping of external systems that can be used to generate topfile data.
'master_tops': dict,
# Whether or not matches from master_tops should be executed before or
# after those from the top file(s).
'master_tops_first': bool,
# A flag that should be set on a top-level master when it is ordering around subordinate masters
# via the use of a salt syndic
'order_masters': bool,
# Whether or not to cache jobs so that they can be examined later on
'job_cache': bool,
# Define a returner to be used as an external job caching storage backend
'ext_job_cache': six.string_types,
# Specify a returner for the master to use as a backend storage system to cache jobs returns
# that it receives
'master_job_cache': six.string_types,
# Specify whether the master should store end times for jobs as returns come in
'job_cache_store_endtime': bool,
# The minion data cache is a cache of information about the minions stored on the master.
# This information is primarily the pillar and grains data. The data is cached in the master
# cachedir under the name of the minion and used to predetermine what minions are expected to
# reply from executions.
'minion_data_cache': bool,
# The number of seconds between AES key rotations on the master
'publish_session': int,
# Defines a salt reactor. See http://docs.saltstack.com/en/latest/topics/reactor/
'reactor': list,
# The TTL for the cache of the reactor configuration
'reactor_refresh_interval': int,
# The number of workers for the runner/wheel in the reactor
'reactor_worker_threads': int,
# The queue size for workers in the reactor
'reactor_worker_hwm': int,
# Defines engines. See https://docs.saltstack.com/en/latest/topics/engines/
'engines': list,
# Whether or not to store runner returns in the job cache
'runner_returns': bool,
'serial': six.string_types,
'search': six.string_types,
# A compound target definition.
# See: http://docs.saltstack.com/en/latest/topics/targeting/nodegroups.html
'nodegroups': (dict, list),
# List-only nodegroups for salt-ssh. Each group must be formed as either a
# comma-separated list, or a YAML list.
'ssh_list_nodegroups': dict,
# By default, salt-ssh uses its own specially-generated RSA key to auth
# against minions. If this is set to True, salt-ssh will look in
# for a key at ~/.ssh/id_rsa, and fall back to using its own specially-
# generated RSA key if that file doesn't exist.
'ssh_use_home_key': bool,
# The logfile location for salt-key
'key_logfile': six.string_types,
# The upper bound for the random number of seconds that a minion should
# delay when starting in up before it connects to a master. This can be
# used to mitigate a thundering-herd scenario when many minions start up
# at once and attempt to all connect immediately to the master
'random_startup_delay': int,
# The source location for the winrepo sls files
# (used by win_pkg.py, minion only)
'winrepo_source_dir': six.string_types,
'winrepo_dir': six.string_types,
'winrepo_dir_ng': six.string_types,
'winrepo_cachefile': six.string_types,
# NOTE: winrepo_branch omitted here because its value could conceivably be
# loaded as a non-string type, which is OK because winrepo will normalize
# them to strings. But rather than include all the possible types it could
# be, we'll just skip type-checking.
'winrepo_cache_expire_max': int,
'winrepo_cache_expire_min': int,
'winrepo_remotes': list,
'winrepo_remotes_ng': list,
'winrepo_ssl_verify': bool,
'winrepo_user': six.string_types,
'winrepo_password': six.string_types,
'winrepo_insecure_auth': bool,
'winrepo_privkey': six.string_types,
'winrepo_pubkey': six.string_types,
'winrepo_passphrase': six.string_types,
'winrepo_refspecs': list,
# Set a hard limit for the amount of memory modules can consume on a minion.
'modules_max_memory': int,
# Blacklist specific core grains to be filtered
'grains_blacklist': list,
# The number of minutes between the minion refreshing its cache of grains
'grains_refresh_every': int,
# Use lspci to gather system data for grains on a minion
'enable_lspci': bool,
# The number of seconds for the salt client to wait for additional syndics to
# check in with their lists of expected minions before giving up
'syndic_wait': int,
# Override Jinja environment option defaults for all templates except sls templates
'jinja_env': dict,
# Set Jinja environment options for sls templates
'jinja_sls_env': dict,
# If this is set to True leading spaces and tabs are stripped from the start
# of a line to a block.
'jinja_lstrip_blocks': bool,
# If this is set to True the first newline after a Jinja block is removed
'jinja_trim_blocks': bool,
# Cache minion ID to file
'minion_id_caching': bool,
# Always generate minion id in lowercase.
'minion_id_lowercase': bool,
# Remove either a single domain (foo.org), or all (True) from a generated minion id.
'minion_id_remove_domain': (six.string_types, bool),
# If set, the master will sign all publications before they are sent out
'sign_pub_messages': bool,
# The size of key that should be generated when creating new keys
'keysize': int,
# The transport system for this daemon. (i.e. zeromq, tcp, detect, etc)
'transport': six.string_types,
# The number of seconds to wait when the client is requesting information about running jobs
'gather_job_timeout': int,
# The number of seconds to wait before timing out an authentication request
'auth_timeout': int,
# The number of attempts to authenticate to a master before giving up
'auth_tries': int,
# The number of attempts to connect to a master before giving up.
# Set this to -1 for unlimited attempts. This allows for a master to have
# downtime and the minion to reconnect to it later when it comes back up.
# In 'failover' mode, it is the number of attempts for each set of masters.
# In this mode, it will cycle through the list of masters for each attempt.
'master_tries': int,
# Never give up when trying to authenticate to a master
'auth_safemode': bool,
# Selects a random master when starting a minion up in multi-master mode or
# when starting a minion with salt-call. ``master`` must be a list.
'random_master': bool,
# An upper bound for the amount of time for a minion to sleep before attempting to
# reauth after a restart.
'random_reauth_delay': int,
# The number of seconds for a syndic to poll for new messages that need to be forwarded
'syndic_event_forward_timeout': float,
# The length that the syndic event queue must hit before events are popped off and forwarded
'syndic_jid_forward_cache_hwm': int,
# Salt SSH configuration
'ssh_passwd': six.string_types,
'ssh_port': six.string_types,
'ssh_sudo': bool,
'ssh_sudo_user': six.string_types,
'ssh_timeout': float,
'ssh_user': six.string_types,
'ssh_scan_ports': six.string_types,
'ssh_scan_timeout': float,
'ssh_identities_only': bool,
'ssh_log_file': six.string_types,
'ssh_config_file': six.string_types,
'ssh_merge_pillar': bool,
'cluster_mode': bool,
'sqlite_queue_dir': six.string_types,
'queue_dirs': list,
# Instructs the minion to ping its master(s) every n number of minutes. Used
# primarily as a mitigation technique against minion disconnects.
'ping_interval': int,
# Instructs the salt CLI to print a summary of a minion responses before returning
'cli_summary': bool,
# The maximum number of minion connections allowed by the master. Can have performance
# implications in large setups.
'max_minions': int,
'username': (type(None), six.string_types),
'password': (type(None), six.string_types),
# Use zmq.SUSCRIBE to limit listening sockets to only process messages bound for them
'zmq_filtering': bool,
# Connection caching. Can greatly speed up salt performance.
'con_cache': bool,
'rotate_aes_key': bool,
# Cache ZeroMQ connections. Can greatly improve salt performance.
'cache_sreqs': bool,
# Can be set to override the python_shell=False default in the cmd module
'cmd_safe': bool,
# Used by salt-api for master requests timeout
'rest_timeout': int,
# If set, all minion exec module actions will be rerouted through sudo as this user
'sudo_user': six.string_types,
# HTTP connection timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_connect_timeout': float,
# HTTP request timeout in seconds. Applied for tornado http fetch functions like cp.get_url
# should be greater than overall download time
'http_request_timeout': float,
# HTTP request max file content size.
'http_max_body': int,
# Delay in seconds before executing bootstrap (Salt Cloud)
'bootstrap_delay': int,
# If a proxymodule has a function called 'grains', then call it during
# regular grains loading and merge the results with the proxy's grains
# dictionary. Otherwise it is assumed that the module calls the grains
# function in a custom way and returns the data elsewhere
#
# Default to False for 2016.3 and 2016.11. Switch to True for 2017.7.0
'proxy_merge_grains_in_module': bool,
# Command to use to restart salt-minion
'minion_restart_command': list,
# Whether or not a minion should send the results of a command back to the master
# Useful when a returner is the source of truth for a job result
'pub_ret': bool,
# HTTP request settings. Used in tornado fetch functions
'user_agent': six.string_types,
# HTTP proxy settings. Used in tornado fetch functions, apt-key etc
'proxy_host': six.string_types,
'proxy_username': six.string_types,
'proxy_password': six.string_types,
'proxy_port': int,
# Exclude list of hostnames from proxy
'no_proxy': list,
# Minion de-dup jid cache max size
'minion_jid_queue_hwm': int,
# Minion data cache driver (one of satl.cache.* modules)
'cache': six.string_types,
# Enables a fast in-memory cache booster and sets the expiration time.
'memcache_expire_seconds': int,
# Set a memcache limit in items (bank + key) per cache storage (driver + driver_opts).
'memcache_max_items': int,
# Each time a cache storage got full cleanup all the expired items not just the oldest one.
'memcache_full_cleanup': bool,
# Enable collecting the memcache stats and log it on `debug` log level.
'memcache_debug': bool,
# Thin and minimal Salt extra modules
'thin_extra_mods': six.string_types,
'min_extra_mods': six.string_types,
# Default returners minion should use. List or comma-delimited string
'return': (six.string_types, list),
# TLS/SSL connection options. This could be set to a dictionary containing arguments
# corresponding to python ssl.wrap_socket method. For details see:
# http://www.tornadoweb.org/en/stable/tcpserver.html#tornado.tcpserver.TCPServer
# http://docs.python.org/2/library/ssl.html#ssl.wrap_socket
# Note: to set enum arguments values like `cert_reqs` and `ssl_version` use constant names
# without ssl module prefix: `CERT_REQUIRED` or `PROTOCOL_SSLv23`.
'ssl': (dict, bool, type(None)),
# Controls how a multi-function job returns its data. If this is False,
# it will return its data using a dictionary with the function name as
# the key. This is compatible with legacy systems. If this is True, it
# will return its data using an array in the same order as the input
# array of functions to execute. This allows for calling the same
# function multiple times in the same multi-function job.
'multifunc_ordered': bool,
# Controls whether beacons are set up before a connection
# to the master is attempted.
'beacons_before_connect': bool,
# Controls whether the scheduler is set up before a connection
# to the master is attempted.
'scheduler_before_connect': bool,
# Whitelist/blacklist specific modules to be synced
'extmod_whitelist': dict,
'extmod_blacklist': dict,
# django auth
'django_auth_path': six.string_types,
'django_auth_settings': six.string_types,
# Number of times to try to auth with the master on a reconnect with the
# tcp transport
'tcp_authentication_retries': int,
# Permit or deny allowing minions to request revoke of its own key
'allow_minion_key_revoke': bool,
# File chunk size for salt-cp
'salt_cp_chunk_size': int,
# Require that the minion sign messages it posts to the master on the event
# bus
'minion_sign_messages': bool,
# Have master drop messages from minions for which their signatures do
# not verify
'drop_messages_signature_fail': bool,
# Require that payloads from minions have a 'sig' entry
# (in other words, require that minions have 'minion_sign_messages'
# turned on)
'require_minion_sign_messages': bool,
# The list of config entries to be passed to external pillar function as
# part of the extra_minion_data param
# Subconfig entries can be specified by using the ':' notation (e.g. key:subkey)
'pass_to_ext_pillars': (six.string_types, list),
# Used by salt.modules.dockermod.compare_container_networks to specify which keys are compared
'docker.compare_container_networks': dict,
# SSDP discovery publisher description.
# Contains publisher configuration and minion mapping.
# Setting it to False disables discovery
'discovery': (dict, bool),
# Scheduler should be a dictionary
'schedule': dict,
# Whether to fire auth events
'auth_events': bool,
# Whether to fire Minion data cache refresh events
'minion_data_cache_events': bool,
# Enable calling ssh minions from the salt master
'enable_ssh_minions': bool,
# Thorium saltenv
'thoriumenv': (type(None), six.string_types),
# Thorium top file location
'thorium_top': six.string_types,
# Use Adler32 hashing algorithm for server_id (default False until Sodium, "adler32" after)
# Possible values are: False, adler32, crc32
'server_id_use_crc': (bool, six.string_types),
# Disable requisites during State runs
'disabled_requisites': (six.string_types, list),
})
# default configurations
DEFAULT_MINION_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'master': 'salt',
'master_type': 'str',
'master_uri_format': 'default',
'source_interface_name': '',
'source_address': '',
'source_ret_port': 0,
'source_publish_port': 0,
'master_port': 4506,
'master_finger': '',
'master_shuffle': False,
'master_alive_interval': 0,
'master_failback': False,
'master_failback_interval': 0,
'verify_master_pubkey_sign': False,
'sign_pub_messages': False,
'always_verify_signature': False,
'master_sign_key_name': 'master_sign',
'syndic_finger': '',
'user': salt.utils.user.get_user(),
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'minion'),
'id': '',
'id_function': {},
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'minion'),
'append_minionid_config_dirs': [],
'cache_jobs': False,
'grains_blacklist': [],
'grains_cache': False,
'grains_cache_expiration': 300,
'grains_deep_merge': False,
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'minion'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion'),
'sock_pool_size': 1,
'backup_mode': '',
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'random_startup_delay': 0,
'failhard': False,
'autoload_dynamic_modules': True,
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'pillarenv_from_saltenv': False,
'pillar_opts': False,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
# ``pillar_cache``, ``pillar_cache_ttl`` and ``pillar_cache_backend``
# are not used on the minion but are unavoidably in the code path
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'minion', 'extmods'),
'state_top': 'top.sls',
'state_top_saltenv': None,
'startup_states': '',
'sls_list': [],
'top_file': '',
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'file_client': 'remote',
'local': False,
'use_master_when_local': False,
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'default_top': 'base',
'fileserver_limit_traversal': False,
'file_recv': False,
'file_recv_max_size': 100,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'unique_jid': False,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'disable_modules': [],
'disable_returners': [],
'whitelist_modules': [],
'module_dirs': [],
'returner_dirs': [],
'grains_dirs': [],
'states_dirs': [],
'render_dirs': [],
'outputter_dirs': [],
'utils_dirs': [],
'publisher_acl': {},
'publisher_acl_blacklist': {},
'providers': {},
'clean_dynamic_modules': True,
'open_mode': False,
'auto_accept': True,
'autosign_timeout': 120,
'multiprocessing': True,
'process_count_max': -1,
'process_count_max_sleep_secs': 10,
'mine_enabled': True,
'mine_return_job': False,
'mine_interval': 60,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'file_buffer_size': 262144,
'tcp_pub_port': 4510,
'tcp_pull_port': 4511,
'tcp_authentication_retries': 5,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'minion'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'max_event_size': 1048576,
'enable_legacy_startup_events': True,
'test': False,
'ext_job_cache': '',
'cython_enable': False,
'enable_gpu_grains': True,
'enable_zip_modules': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'snapper_states': False,
'snapper_states_config': 'root',
'acceptance_wait_time': 10,
'acceptance_wait_time_max': 0,
'rejected_retry': False,
'loop_interval': 1,
'verify_env': True,
'grains': {},
'permissive_pki_access': False,
'default_include': 'minion.d/*.conf',
'update_url': False,
'update_restart_services': [],
'retry_dns': 30,
'retry_dns_count': None,
'resolve_dns_fallback': True,
'recon_max': 10000,
'recon_default': 1000,
'recon_randomize': True,
'return_retry_timer': 5,
'return_retry_timer_max': 10,
'random_reauth_delay': 10,
'winrepo_source_dir': 'salt://win/repo-ng/',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_cache_expire_max': 21600,
'winrepo_cache_expire_min': 1800,
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-minion.pid'),
'range_server': 'range:80',
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'modules_max_memory': -1,
'grains_refresh_every': 0,
'minion_id_caching': True,
'minion_id_lowercase': False,
'minion_id_remove_domain': False,
'keysize': 2048,
'transport': 'zeromq',
'auth_timeout': 5,
'auth_tries': 7,
'master_tries': _MASTER_TRIES,
'master_tops_first': False,
'auth_safemode': False,
'random_master': False,
'cluster_mode': False,
'restart_on_error': False,
'ping_interval': 0,
'username': None,
'password': None,
'zmq_filtering': False,
'zmq_monitor': False,
'cache_sreqs': True,
'cmd_safe': True,
'sudo_user': '',
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'event_match_type': 'startswith',
'minion_restart_command': [],
'pub_ret': True,
'user_agent': '',
'proxy_host': '',
'proxy_username': '',
'proxy_password': '',
'proxy_port': 0,
'minion_jid_queue_hwm': 100,
'ssl': None,
'multifunc_ordered': False,
'beacons_before_connect': False,
'scheduler_before_connect': False,
'cache': 'localfs',
'salt_cp_chunk_size': 65536,
'extmod_whitelist': {},
'extmod_blacklist': {},
'minion_sign_messages': False,
'docker.compare_container_networks': {
'static': ['Aliases', 'Links', 'IPAMConfig'],
'automatic': ['IPAddress', 'Gateway',
'GlobalIPv6Address', 'IPv6Gateway'],
},
'discovery': False,
'schedule': {},
'ssh_merge_pillar': True,
'server_id_use_crc': False,
'disabled_requisites': [],
})
DEFAULT_MASTER_OPTS = immutabletypes.freeze({
'interface': '0.0.0.0',
'publish_port': 4505,
'zmq_backlog': 1000,
'pub_hwm': 1000,
'auth_mode': 1,
'user': _MASTER_USER,
'worker_threads': 5,
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'master'),
'sock_pool_size': 1,
'ret_port': 4506,
'timeout': 5,
'keep_jobs': 24,
'archive_jobs': False,
'root_dir': salt.syspaths.ROOT_DIR,
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'master'),
'key_cache': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'master'),
'file_roots': {
'base': [salt.syspaths.BASE_FILE_ROOTS_DIR,
salt.syspaths.SPM_FORMULA_PATH]
},
'master_roots': {
'base': [salt.syspaths.BASE_MASTER_ROOTS_DIR],
},
'pillar_roots': {
'base': [salt.syspaths.BASE_PILLAR_ROOTS_DIR,
salt.syspaths.SPM_PILLAR_PATH]
},
'on_demand_ext_pillar': ['libvirt', 'virtkey'],
'decrypt_pillar': [],
'decrypt_pillar_delimiter': ':',
'decrypt_pillar_default': 'gpg',
'decrypt_pillar_renderers': ['gpg'],
'thoriumenv': None,
'thorium_top': 'top.sls',
'thorium_interval': 0.5,
'thorium_roots': {
'base': [salt.syspaths.BASE_THORIUM_ROOTS_DIR],
},
'top_file_merging_strategy': 'merge',
'env_order': [],
'saltenv': None,
'lock_saltenv': False,
'pillarenv': None,
'default_top': 'base',
'file_client': 'local',
'local': True,
# Update intervals
'roots_update_interval': DEFAULT_INTERVAL,
'azurefs_update_interval': DEFAULT_INTERVAL,
'gitfs_update_interval': DEFAULT_INTERVAL,
'hgfs_update_interval': DEFAULT_INTERVAL,
'minionfs_update_interval': DEFAULT_INTERVAL,
's3fs_update_interval': DEFAULT_INTERVAL,
'svnfs_update_interval': DEFAULT_INTERVAL,
'git_pillar_base': 'master',
'git_pillar_branch': 'master',
'git_pillar_env': '',
'git_pillar_root': '',
'git_pillar_ssl_verify': True,
'git_pillar_global_lock': True,
'git_pillar_user': '',
'git_pillar_password': '',
'git_pillar_insecure_auth': False,
'git_pillar_privkey': '',
'git_pillar_pubkey': '',
'git_pillar_passphrase': '',
'git_pillar_refspecs': _DFLT_REFSPECS,
'git_pillar_includes': True,
'git_pillar_verify_config': True,
'gitfs_remotes': [],
'gitfs_mountpoint': '',
'gitfs_root': '',
'gitfs_base': 'master',
'gitfs_user': '',
'gitfs_password': '',
'gitfs_insecure_auth': False,
'gitfs_privkey': '',
'gitfs_pubkey': '',
'gitfs_passphrase': '',
'gitfs_env_whitelist': [],
'gitfs_env_blacklist': [],
'gitfs_saltenv_whitelist': [],
'gitfs_saltenv_blacklist': [],
'gitfs_global_lock': True,
'gitfs_ssl_verify': True,
'gitfs_saltenv': [],
'gitfs_ref_types': ['branch', 'tag', 'sha'],
'gitfs_refspecs': _DFLT_REFSPECS,
'gitfs_disable_saltenv_mapping': False,
'hgfs_remotes': [],
'hgfs_mountpoint': '',
'hgfs_root': '',
'hgfs_base': 'default',
'hgfs_branch_method': 'branches',
'hgfs_env_whitelist': [],
'hgfs_env_blacklist': [],
'hgfs_saltenv_whitelist': [],
'hgfs_saltenv_blacklist': [],
'show_timeout': True,
'show_jid': False,
'unique_jid': False,
'svnfs_remotes': [],
'svnfs_mountpoint': '',
'svnfs_root': '',
'svnfs_trunk': 'trunk',
'svnfs_branches': 'branches',
'svnfs_tags': 'tags',
'svnfs_env_whitelist': [],
'svnfs_env_blacklist': [],
'svnfs_saltenv_whitelist': [],
'svnfs_saltenv_blacklist': [],
'max_event_size': 1048576,
'master_stats': False,
'master_stats_event_iter': 60,
'minionfs_env': 'base',
'minionfs_mountpoint': '',
'minionfs_whitelist': [],
'minionfs_blacklist': [],
'ext_pillar': [],
'pillar_version': 2,
'pillar_opts': False,
'pillar_safe_render_error': True,
'pillar_source_merging_strategy': 'smart',
'pillar_merge_lists': False,
'pillar_includes_override_sls': False,
'pillar_cache': False,
'pillar_cache_ttl': 3600,
'pillar_cache_backend': 'disk',
'ping_on_rotate': False,
'peer': {},
'preserve_minion_cache': False,
'syndic_master': 'masterofmasters',
'syndic_failover': 'random',
'syndic_forward_all_events': False,
'syndic_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'syndic'),
'syndic_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-syndic.pid'),
'outputter_dirs': [],
'runner_dirs': [],
'utils_dirs': [],
'client_acl_verify': True,
'publisher_acl': {},
'publisher_acl_blacklist': {},
'sudo_acl': False,
'external_auth': {},
'token_expire': 43200,
'token_expire_user_override': False,
'permissive_acl': False,
'keep_acl_in_token': False,
'eauth_acl_module': '',
'eauth_tokens': 'localfs',
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'extmods'),
'module_dirs': [],
'file_recv': False,
'file_recv_max_size': 100,
'file_buffer_size': 1048576,
'file_ignore_regex': [],
'file_ignore_glob': [],
'fileserver_backend': ['roots'],
'fileserver_followsymlinks': True,
'fileserver_ignoresymlinks': False,
'fileserver_limit_traversal': False,
'fileserver_verify_config': True,
'max_open_files': 100000,
'hash_type': 'sha256',
'optimization_order': [0, 1, 2],
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'master'),
'open_mode': False,
'auto_accept': False,
'renderer': 'jinja|yaml',
'renderer_whitelist': [],
'renderer_blacklist': [],
'failhard': False,
'state_top': 'top.sls',
'state_top_saltenv': None,
'master_tops': {},
'master_tops_first': False,
'order_masters': False,
'job_cache': True,
'ext_job_cache': '',
'master_job_cache': 'local_cache',
'job_cache_store_endtime': False,
'minion_data_cache': True,
'enforce_mine_cache': False,
'ipc_mode': _DFLT_IPC_MODE,
'ipc_write_buffer': _DFLT_IPC_WBUFFER,
'ipc_so_rcvbuf': None,
'ipc_so_sndbuf': None,
'ipc_so_backlog': 128,
'ipv6': None,
'tcp_master_pub_port': 4512,
'tcp_master_pull_port': 4513,
'tcp_master_publish_pull': 4514,
'tcp_master_workers': 4515,
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'master'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-master.pid'),
'publish_session': 86400,
'range_server': 'range:80',
'reactor': [],
'reactor_refresh_interval': 60,
'reactor_worker_threads': 10,
'reactor_worker_hwm': 10000,
'engines': [],
'event_return': '',
'event_return_queue': 0,
'event_return_whitelist': [],
'event_return_blacklist': [],
'event_match_type': 'startswith',
'runner_returns': True,
'serial': 'msgpack',
'test': False,
'state_verbose': True,
'state_output': 'full',
'state_output_diff': False,
'state_auto_order': True,
'state_events': False,
'state_aggregate': False,
'search': '',
'loop_interval': 60,
'nodegroups': {},
'ssh_list_nodegroups': {},
'ssh_use_home_key': False,
'cython_enable': False,
'enable_gpu_grains': False,
# XXX: Remove 'key_logfile' support in 2014.1.0
'key_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'key'),
'verify_env': True,
'permissive_pki_access': False,
'key_pass': None,
'signing_key_pass': None,
'default_include': 'master.d/*.conf',
'winrepo_dir': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo'),
'winrepo_dir_ng': os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'win', 'repo-ng'),
'winrepo_cachefile': 'winrepo.p',
'winrepo_remotes': ['https://github.com/saltstack/salt-winrepo.git'],
'winrepo_remotes_ng': ['https://github.com/saltstack/salt-winrepo-ng.git'],
'winrepo_branch': 'master',
'winrepo_ssl_verify': True,
'winrepo_user': '',
'winrepo_password': '',
'winrepo_insecure_auth': False,
'winrepo_privkey': '',
'winrepo_pubkey': '',
'winrepo_passphrase': '',
'winrepo_refspecs': _DFLT_REFSPECS,
'syndic_wait': 5,
'jinja_env': {},
'jinja_sls_env': {},
'jinja_lstrip_blocks': False,
'jinja_trim_blocks': False,
'tcp_keepalive': True,
'tcp_keepalive_idle': 300,
'tcp_keepalive_cnt': -1,
'tcp_keepalive_intvl': -1,
'sign_pub_messages': True,
'keysize': 2048,
'transport': 'zeromq',
'gather_job_timeout': 10,
'syndic_event_forward_timeout': 0.5,
'syndic_jid_forward_cache_hwm': 100,
'regen_thin': False,
'ssh_passwd': '',
'ssh_priv_passwd': '',
'ssh_port': '22',
'ssh_sudo': False,
'ssh_sudo_user': '',
'ssh_timeout': 60,
'ssh_user': 'root',
'ssh_scan_ports': '22',
'ssh_scan_timeout': 0.01,
'ssh_identities_only': False,
'ssh_log_file': os.path.join(salt.syspaths.LOGS_DIR, 'ssh'),
'ssh_config_file': os.path.join(salt.syspaths.HOME_DIR, '.ssh', 'config'),
'cluster_mode': False,
'sqlite_queue_dir': os.path.join(salt.syspaths.CACHE_DIR, 'master', 'queues'),
'queue_dirs': [],
'cli_summary': False,
'max_minions': 0,
'master_sign_key_name': 'master_sign',
'master_sign_pubkey': False,
'master_pubkey_signature': 'master_pubkey_signature',
'master_use_pubkey_signature': False,
'zmq_filtering': False,
'zmq_monitor': False,
'con_cache': False,
'rotate_aes_key': True,
'cache_sreqs': True,
'dummy_pub': False,
'http_connect_timeout': 20.0, # tornado default - 20 seconds
'http_request_timeout': 1 * 60 * 60.0, # 1 hour
'http_max_body': 100 * 1024 * 1024 * 1024, # 100GB
'python2_bin': 'python2',
'python3_bin': 'python3',
'cache': 'localfs',
'memcache_expire_seconds': 0,
'memcache_max_items': 1024,
'memcache_full_cleanup': False,
'memcache_debug': False,
'thin_extra_mods': '',
'min_extra_mods': '',
'ssl': None,
'extmod_whitelist': {},
'extmod_blacklist': {},
'clean_dynamic_modules': True,
'django_auth_path': '',
'django_auth_settings': '',
'allow_minion_key_revoke': True,
'salt_cp_chunk_size': 98304,
'require_minion_sign_messages': False,
'drop_messages_signature_fail': False,
'discovery': False,
'schedule': {},
'auth_events': True,
'minion_data_cache_events': True,
'enable_ssh_minions': False,
})
# ----- Salt Proxy Minion Configuration Defaults ----------------------------------->
# These are merged with DEFAULT_MINION_OPTS since many of them also apply here.
DEFAULT_PROXY_MINION_OPTS = immutabletypes.freeze({
'conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'proxy'),
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'proxy'),
'add_proxymodule_to_opts': False,
'proxy_merge_grains_in_module': True,
'extension_modules': os.path.join(salt.syspaths.CACHE_DIR, 'proxy', 'extmods'),
'append_minionid_config_dirs': ['cachedir', 'pidfile', 'default_include', 'extension_modules'],
'default_include': 'proxy.d/*.conf',
'proxy_merge_pillar_in_opts': False,
'proxy_deep_merge_pillar_in_opts': False,
'proxy_merge_pillar_in_opts_strategy': 'smart',
'proxy_mines_pillar': True,
# By default, proxies will preserve the connection.
# If this option is set to False,
# the connection with the remote dumb device
# is closed after each command request.
'proxy_always_alive': True,
'proxy_keep_alive': True, # by default will try to keep alive the connection
'proxy_keep_alive_interval': 1, # frequency of the proxy keepalive in minutes
'pki_dir': os.path.join(salt.syspaths.CONFIG_DIR, 'pki', 'proxy'),
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'proxy'),
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'proxy'),
})
# ----- Salt Cloud Configuration Defaults ----------------------------------->
DEFAULT_CLOUD_OPTS = immutabletypes.freeze({
'verify_env': True,
'default_include': 'cloud.conf.d/*.conf',
# Global defaults
'ssh_auth': '',
'cachedir': os.path.join(salt.syspaths.CACHE_DIR, 'cloud'),
'keysize': 4096,
'os': '',
'script': 'bootstrap-salt',
'start_action': None,
'enable_hard_maps': False,
'delete_sshkeys': False,
# Custom deploy scripts
'deploy_scripts_search_path': 'cloud.deploy.d',
# Logging defaults
'log_file': os.path.join(salt.syspaths.LOGS_DIR, 'cloud'),
'log_level': 'warning',
'log_level_logfile': None,
'log_datefmt': _DFLT_LOG_DATEFMT,
'log_datefmt_logfile': _DFLT_LOG_DATEFMT_LOGFILE,
'log_fmt_console': _DFLT_LOG_FMT_CONSOLE,
'log_fmt_logfile': _DFLT_LOG_FMT_LOGFILE,
'log_fmt_jid': _DFLT_LOG_FMT_JID,
'log_granular_levels': {},
'log_rotate_max_bytes': 0,
'log_rotate_backup_count': 0,
'bootstrap_delay': None,
'cache': 'localfs',
})
DEFAULT_API_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by Salt-API --------------------->
'api_pidfile': os.path.join(salt.syspaths.PIDFILE_DIR, 'salt-api.pid'),
'api_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'api'),
'rest_timeout': 300,
# <---- Salt master settings overridden by Salt-API ----------------------
})
DEFAULT_SPM_OPTS = immutabletypes.freeze({
# ----- Salt master settings overridden by SPM --------------------->
'spm_conf_file': os.path.join(salt.syspaths.CONFIG_DIR, 'spm'),
'formula_path': salt.syspaths.SPM_FORMULA_PATH,
'pillar_path': salt.syspaths.SPM_PILLAR_PATH,
'reactor_path': salt.syspaths.SPM_REACTOR_PATH,
'spm_logfile': os.path.join(salt.syspaths.LOGS_DIR, 'spm'),
'spm_default_include': 'spm.d/*.conf',
# spm_repos_config also includes a .d/ directory
'spm_repos_config': '/etc/salt/spm.repos',
'spm_cache_dir': os.path.join(salt.syspaths.CACHE_DIR, 'spm'),
'spm_build_dir': os.path.join(salt.syspaths.SRV_ROOT_DIR, 'spm_build'),
'spm_build_exclude': ['CVS', '.hg', '.git', '.svn'],
'spm_db': os.path.join(salt.syspaths.CACHE_DIR, 'spm', 'packages.db'),
'cache': 'localfs',
'spm_repo_dups': 'ignore',
# If set, spm_node_type will be either master or minion, but they should
# NOT be a default
'spm_node_type': '',
'spm_share_dir': os.path.join(salt.syspaths.SHARE_DIR, 'spm'),
# <---- Salt master settings overridden by SPM ----------------------
})
VM_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.profiles.d/*.conf',
})
PROVIDER_CONFIG_DEFAULTS = immutabletypes.freeze({
'default_include': 'cloud.providers.d/*.conf',
})
# <---- Salt Cloud Configuration Defaults ------------------------------------
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
def _validate_pillar_roots(pillar_roots):
'''
If the pillar_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(pillar_roots, dict):
log.warning('The pillar_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])}
return _normalize_roots(pillar_roots)
def _validate_file_roots(file_roots):
'''
If the file_roots option has a key that is None then we will error out,
just replace it with an empty list
'''
if not isinstance(file_roots, dict):
log.warning('The file_roots parameter is not properly formatted,'
' using defaults')
return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
return _normalize_roots(file_roots)
def _expand_glob_path(file_roots):
'''
Applies shell globbing to a set of directories and returns
the expanded paths
'''
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
else:
unglobbed_path.append(path)
except Exception:
unglobbed_path.append(path)
return unglobbed_path
def _validate_opts(opts):
'''
Check that all of the types of values passed into the config are
of the right types
'''
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of the type
# passed.
return valid_type.__name__
else:
def get_types(types, type_tuple):
for item in type_tuple:
if isinstance(item, tuple):
get_types(types, item)
else:
try:
types.append(item.__name__)
except AttributeError:
log.warning(
'Unable to interpret type %s while validating '
'configuration', item
)
types = []
get_types(types, valid_type)
ret = ', '.join(types[:-1])
ret += ' or ' + types[-1]
return ret
errors = []
err = (
'Config option \'{0}\' with value {1} has an invalid type of {2}, a '
'{3} is required for this option'
)
for key, val in six.iteritems(opts):
if key in VALID_OPTS:
if val is None:
if VALID_OPTS[key] is None:
continue
else:
try:
if None in VALID_OPTS[key]:
continue
except TypeError:
# VALID_OPTS[key] is not iterable and not None
pass
if isinstance(val, VALID_OPTS[key]):
continue
# We don't know what data type sdb will return at run-time so we
# simply cannot check it for correctness here at start-time.
if isinstance(val, six.string_types) and val.startswith('sdb://'):
continue
if hasattr(VALID_OPTS[key], '__call__'):
try:
VALID_OPTS[key](val)
if isinstance(val, (list, dict)):
# We'll only get here if VALID_OPTS[key] is str or
# bool, and the passed value is a list/dict. Attempting
# to run int() or float() on a list/dict will raise an
# exception, but running str() or bool() on it will
# pass despite not being the correct type.
errors.append(
err.format(
key,
val,
type(val).__name__,
VALID_OPTS[key].__name__
)
)
except (TypeError, ValueError):
errors.append(
err.format(key,
val,
type(val).__name__,
VALID_OPTS[key].__name__)
)
continue
errors.append(
err.format(key,
val,
type(val).__name__,
format_multi_opt(VALID_OPTS[key]))
)
# Convert list to comma-delimited string for 'return' config option
if isinstance(opts.get('return'), list):
opts['return'] = ','.join(opts['return'])
for error in errors:
log.warning(error)
if errors:
return False
return True
def _validate_ssh_minion_opts(opts):
'''
Ensure we're not using any invalid ssh_minion_opts. We want to make sure
that the ssh_minion_opts does not override any pillar or fileserver options
inherited from the master config. To add other items, modify the if
statement in the for loop below.
'''
ssh_minion_opts = opts.get('ssh_minion_opts', {})
if not isinstance(ssh_minion_opts, dict):
log.error('Invalidly-formatted ssh_minion_opts')
opts.pop('ssh_minion_opts')
for opt_name in list(ssh_minion_opts):
if re.match('^[a-z0-9]+fs_', opt_name, flags=re.IGNORECASE) \
or ('pillar' in opt_name and not 'ssh_merge_pillar' == opt_name) \
or opt_name in ('fileserver_backend',):
log.warning(
'\'%s\' is not a valid ssh_minion_opts parameter, ignoring',
opt_name
)
ssh_minion_opts.pop(opt_name)
def _append_domain(opts):
'''
Append a domain to the existing id if it doesn't already exist
'''
# Domain already exists
if opts['id'].endswith(opts['append_domain']):
return opts['id']
# Trailing dot should mean an FQDN that is terminated, leave it alone.
if opts['id'].endswith('.'):
return opts['id']
return '{0[id]}.{0[append_domain]}'.format(opts)
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
except salt.utils.yaml.YAMLError as err:
message = 'Error parsing configuration file: {0} - {1}'.format(path, err)
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# only interpret documents as a valid conf, not things like strings,
# which might have been caused by invalid yaml syntax
if not isinstance(conf_opts, dict):
message = 'Error parsing configuration file: {0} - conf ' \
'should be a document, not {1}.'.format(path, type(conf_opts))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
# allow using numeric ids: convert int to string
if 'id' in conf_opts:
if not isinstance(conf_opts['id'], six.string_types):
conf_opts['id'] = six.text_type(conf_opts['id'])
else:
conf_opts['id'] = salt.utils.data.decode(conf_opts['id'])
return conf_opts
def _absolute_path(path, relative_to=None):
'''
Return an absolute path. In case ``relative_to`` is passed and ``path`` is
not an absolute path, we try to prepend ``relative_to`` to ``path``and if
that path exists, return that one
'''
if path and os.path.isabs(path):
return path
if path and relative_to is not None:
_abspath = os.path.join(relative_to, path)
if os.path.isfile(_abspath):
log.debug(
'Relative path \'%s\' converted to existing absolute path '
'\'%s\'', path, _abspath
)
return _abspath
return path
def load_config(path, env_var, default_path=None, exit_on_config_errors=True):
'''
Returns configuration dict from parsing either the file described by
``path`` or the environment variable described by ``env_var`` as YAML.
'''
if path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if default_path is None:
# This is most likely not being used from salt, i.e., could be salt-cloud
# or salt-api which have not yet migrated to the new default_path
# argument. Let's issue a warning message that the environ vars won't
# work.
import inspect
previous_frame = inspect.getframeinfo(inspect.currentframe().f_back)
log.warning(
"The function '%s()' defined in '%s' is not yet using the "
"new 'default_path' argument to `salt.config.load_config()`. "
"As such, the '%s' environment variable will be ignored",
previous_frame.function, previous_frame.filename, env_var
)
# In this case, maintain old behavior
default_path = DEFAULT_MASTER_OPTS['conf_file']
# Default to the environment variable path, if it exists
env_path = os.environ.get(env_var, path)
if not env_path or not os.path.isfile(env_path):
env_path = path
# If non-default path from `-c`, use that over the env variable
if path != default_path:
env_path = path
path = env_path
# If the configuration file is missing, attempt to copy the template,
# after removing the first header line.
if not os.path.isfile(path):
template = '{0}.template'.format(path)
if os.path.isfile(template):
log.debug('Writing %s based on %s', path, template)
with salt.utils.files.fopen(path, 'w') as out:
with salt.utils.files.fopen(template, 'r') as ifile:
ifile.readline() # skip first line
out.write(ifile.read())
opts = {}
if salt.utils.validate.path.is_readable(path):
try:
opts = _read_conf_file(path)
opts['conf_file'] = path
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
log.debug('Missing configuration file: %s', path)
return opts
def include_config(include, orig_path, verbose, exit_on_config_errors=False):
'''
Parses extra configuration file(s) specified in an include list in the
main config file.
'''
# Protect against empty option
if not include:
return {}
if orig_path is None:
# When the passed path is None, we just want the configuration
# defaults, not actually loading the whole configuration.
return {}
if isinstance(include, six.string_types):
include = [include]
configuration = {}
for path in include:
# Allow for includes like ~/foo
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(orig_path), path)
# Catch situation where user typos path in configuration; also warns
# for empty include directory (which might be by design)
glob_matches = glob.glob(path)
if not glob_matches:
if verbose:
log.warning(
'Warning parsing configuration file: "include" path/glob '
"'%s' matches no files", path
)
for fn_ in sorted(glob_matches):
log.debug('Including configuration from \'%s\'', fn_)
try:
opts = _read_conf_file(fn_)
except salt.exceptions.SaltConfigurationError as error:
log.error(error)
if exit_on_config_errors:
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
else:
# Initialize default config if we wish to skip config errors
opts = {}
schedule = opts.get('schedule', {})
if schedule and 'schedule' in configuration:
configuration['schedule'].update(schedule)
include = opts.get('include', [])
if include:
opts.update(include_config(include, fn_, verbose))
salt.utils.dictupdate.update(configuration, opts, True, True)
return configuration
def prepend_root_dir(opts, path_options):
'''
Prepends the options that represent filesystem paths with value of the
'root_dir' option.
'''
root_dir = os.path.abspath(opts['root_dir'])
def_root_dir = salt.syspaths.ROOT_DIR.rstrip(os.sep)
for path_option in path_options:
if path_option in opts:
path = opts[path_option]
tmp_path_def_root_dir = None
tmp_path_root_dir = None
# When running testsuite, salt.syspaths.ROOT_DIR is often empty
if path == def_root_dir or path.startswith(def_root_dir + os.sep):
# Remove the default root dir prefix
tmp_path_def_root_dir = path[len(def_root_dir):]
if root_dir and (path == root_dir or
path.startswith(root_dir + os.sep)):
# Remove the root dir prefix
tmp_path_root_dir = path[len(root_dir):]
if tmp_path_def_root_dir and not tmp_path_root_dir:
# Just the default root dir matched
path = tmp_path_def_root_dir
elif tmp_path_root_dir and not tmp_path_def_root_dir:
# Just the root dir matched
path = tmp_path_root_dir
elif tmp_path_def_root_dir and tmp_path_root_dir:
# In this case both the default root dir and the override root
# dir matched; this means that either
# def_root_dir is a substring of root_dir or vice versa
# We must choose the most specific path
if def_root_dir in root_dir:
path = tmp_path_root_dir
else:
path = tmp_path_def_root_dir
elif salt.utils.platform.is_windows() and not os.path.splitdrive(path)[0]:
# In windows, os.path.isabs resolves '/' to 'C:\\' or whatever
# the root drive is. This elif prevents the next from being
# hit, so that the root_dir is prefixed in cases where the
# drive is not prefixed on a config option
pass
elif os.path.isabs(path):
# Absolute path (not default or overridden root_dir)
# No prepending required
continue
# Prepending the root dir
opts[path_option] = salt.utils.path.join(root_dir, path)
def insert_system_path(opts, paths):
'''
Inserts path into python path taking into consideration 'root_dir' option.
'''
if isinstance(paths, six.string_types):
paths = [paths]
for path in paths:
path_options = {'path': path, 'root_dir': opts['root_dir']}
prepend_root_dir(path_options, path_options)
if (os.path.isdir(path_options['path'])
and path_options['path'] not in sys.path):
sys.path.insert(0, path_options['path'])
def minion_config(path,
env_var='SALT_MINION_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None,
role='minion'):
'''
Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
minion_opts = salt.config.minion_config('/etc/salt/minion')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'minion')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
opts['__role'] = role
apply_sdb(opts)
_validate_opts(opts)
return opts
def proxy_config(path,
env_var='SALT_PROXY_CONFIG',
defaults=None,
cache_minion_id=False,
ignore_config_errors=True,
minion_id=None):
'''
Reads in the proxy minion configuration file and sets up special options
This is useful for Minion-side operations, such as the
:py:class:`~salt.client.Caller` class, and manually running the loader
interface.
.. code-block:: python
import salt.config
proxy_opts = salt.config.proxy_config('/etc/salt/proxy')
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
defaults.update(DEFAULT_PROXY_MINION_OPTS)
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'proxy')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_PROXY_MINION_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=not ignore_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=not ignore_config_errors))
opts = apply_minion_config(overrides, defaults,
cache_minion_id=cache_minion_id,
minion_id=minion_id)
apply_sdb(opts)
_validate_opts(opts)
return opts
def syndic_config(master_config_path,
minion_config_path,
master_env_var='SALT_MASTER_CONFIG',
minion_env_var='SALT_MINION_CONFIG',
minion_defaults=None,
master_defaults=None):
if minion_defaults is None:
minion_defaults = DEFAULT_MINION_OPTS.copy()
if master_defaults is None:
master_defaults = DEFAULT_MASTER_OPTS.copy()
opts = {}
master_opts = master_config(
master_config_path, master_env_var, master_defaults
)
minion_opts = minion_config(
minion_config_path, minion_env_var, minion_defaults
)
opts['_minion_conf_file'] = master_opts['conf_file']
opts['_master_conf_file'] = minion_opts['conf_file']
opts.update(master_opts)
opts.update(minion_opts)
syndic_opts = {
'__role': 'syndic',
'root_dir': opts.get('root_dir', salt.syspaths.ROOT_DIR),
'pidfile': opts.get('syndic_pidfile', 'salt-syndic.pid'),
'log_file': opts.get('syndic_log_file', 'salt-syndic.log'),
'log_level': master_opts['log_level'],
'id': minion_opts['id'],
'pki_dir': minion_opts['pki_dir'],
'master': opts['syndic_master'],
'interface': master_opts['interface'],
'master_port': int(
opts.get(
# The user has explicitly defined the syndic master port
'syndic_master_port',
opts.get(
# No syndic_master_port, grab master_port from opts
'master_port',
# No master_opts, grab from the provided minion defaults
minion_defaults.get(
'master_port',
# Not on the provided minion defaults, load from the
# static minion defaults
DEFAULT_MINION_OPTS['master_port']
)
)
)
),
'user': opts.get('syndic_user', opts['user']),
'sock_dir': os.path.join(
opts['cachedir'], opts.get('syndic_sock_dir', opts['sock_dir'])
),
'sock_pool_size': master_opts['sock_pool_size'],
'cachedir': master_opts['cachedir'],
}
opts.update(syndic_opts)
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'autosign_grains_dir'
]
for config_key in ('log_file', 'key_logfile', 'syndic_log_file'):
# If this is not a URI and instead a local path
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
return opts
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb_get(sdb_opts, opts)
elif isinstance(sdb_opts, dict):
for key, value in six.iteritems(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
elif isinstance(sdb_opts, list):
for key, value in enumerate(sdb_opts):
if value is None:
continue
sdb_opts[key] = apply_sdb(opts, value)
return sdb_opts
# ----- Salt Cloud Configuration Functions ---------------------------------->
def cloud_config(path=None, env_var='SALT_CLOUD_CONFIG', defaults=None,
master_config_path=None, master_config=None,
providers_config_path=None, providers_config=None,
profiles_config_path=None, profiles_config=None):
'''
Read in the Salt Cloud config and return the dict
'''
if path:
config_dir = os.path.dirname(path)
else:
config_dir = salt.syspaths.CONFIG_DIR
# Load the cloud configuration
overrides = load_config(
path,
env_var,
os.path.join(config_dir, 'cloud')
)
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
# Set defaults early to override Salt Master's default config values later
defaults.update(overrides)
overrides = defaults
# Load cloud configuration from any default or provided includes
overrides.update(
salt.config.include_config(overrides['default_include'], config_dir, verbose=False)
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(include, config_dir, verbose=True)
)
# The includes have been evaluated, let's see if master, providers and
# profiles configuration settings have been included and if not, set the
# default value
if 'master_config' in overrides and master_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
master_config_path = overrides['master_config']
elif 'master_config' not in overrides and not master_config \
and not master_config_path:
# The configuration setting is not being provided in the main cloud
# configuration file, and
master_config_path = os.path.join(config_dir, 'master')
# Convert relative to absolute paths if necessary
master_config_path = _absolute_path(master_config_path, config_dir)
if 'providers_config' in overrides and providers_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
providers_config_path = overrides['providers_config']
elif 'providers_config' not in overrides and not providers_config \
and not providers_config_path:
providers_config_path = os.path.join(config_dir, 'cloud.providers')
# Convert relative to absolute paths if necessary
providers_config_path = _absolute_path(providers_config_path, config_dir)
if 'profiles_config' in overrides and profiles_config_path is None:
# The configuration setting is being specified in the main cloud
# configuration file
profiles_config_path = overrides['profiles_config']
elif 'profiles_config' not in overrides and not profiles_config \
and not profiles_config_path:
profiles_config_path = os.path.join(config_dir, 'cloud.profiles')
# Convert relative to absolute paths if necessary
profiles_config_path = _absolute_path(profiles_config_path, config_dir)
# Prepare the deploy scripts search path
deploy_scripts_search_path = overrides.get(
'deploy_scripts_search_path',
defaults.get('deploy_scripts_search_path', 'cloud.deploy.d')
)
if isinstance(deploy_scripts_search_path, six.string_types):
deploy_scripts_search_path = [deploy_scripts_search_path]
# Check the provided deploy scripts search path removing any non existing
# entries.
for idx, entry in enumerate(deploy_scripts_search_path[:]):
if not os.path.isabs(entry):
# Let's try adding the provided path's directory name turns the
# entry into a proper directory
entry = os.path.join(config_dir, entry)
if os.path.isdir(entry):
# Path exists, let's update the entry (its path might have been
# made absolute)
deploy_scripts_search_path[idx] = entry
continue
# It's not a directory? Remove it from the search path
deploy_scripts_search_path.pop(idx)
# Add the built-in scripts directory to the search path (last resort)
deploy_scripts_search_path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
'cloud',
'deploy'
)
)
)
# Let's make the search path a tuple and add it to the overrides.
overrides.update(
deploy_scripts_search_path=tuple(deploy_scripts_search_path)
)
# Grab data from the 4 sources
# 1st - Master config
if master_config_path is not None and master_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `master_config` or `master_config_path`, not both.'
)
elif master_config_path is None and master_config is None:
master_config = salt.config.master_config(
overrides.get(
# use the value from the cloud config file
'master_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'master')
)
)
elif master_config_path is not None and master_config is None:
master_config = salt.config.master_config(master_config_path)
# cloud config has a separate cachedir
del master_config['cachedir']
# 2nd - salt-cloud configuration which was loaded before so we could
# extract the master configuration file if needed.
# Override master configuration with the salt cloud(current overrides)
master_config.update(overrides)
# We now set the overridden master_config as the overrides
overrides = master_config
if providers_config_path is not None and providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `providers_config` or `providers_config_path`, '
'not both.'
)
elif providers_config_path is None and providers_config is None:
providers_config_path = overrides.get(
# use the value from the cloud config file
'providers_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
if profiles_config_path is not None and profiles_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Only pass `profiles_config` or `profiles_config_path`, not both.'
)
elif profiles_config_path is None and profiles_config is None:
profiles_config_path = overrides.get(
# use the value from the cloud config file
'profiles_config',
# if not found, use the default path
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
# Apply the salt-cloud configuration
opts = apply_cloud_config(overrides, defaults)
# 3rd - Include Cloud Providers
if 'providers' in opts:
if providers_config is not None:
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the passing a pre-configured providers configuration '
'dictionary.'
)
if providers_config_path is not None:
providers_confd = os.path.join(
os.path.dirname(providers_config_path),
'cloud.providers.d', '*'
)
if (os.path.isfile(providers_config_path) or
glob.glob(providers_confd)):
raise salt.exceptions.SaltCloudConfigError(
'Do not mix the old cloud providers configuration with '
'the new one. The providers configuration should now go '
'in the file `{0}` or a separate `*.conf` file within '
'`cloud.providers.d/` which is relative to `{0}`.'.format(
os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
)
# No exception was raised? It's the old configuration alone
providers_config = opts['providers']
elif providers_config_path is not None:
# Load from configuration file, even if that files does not exist since
# it will be populated with defaults.
providers_config = cloud_providers_config(providers_config_path)
# Let's assign back the computed providers configuration
opts['providers'] = providers_config
# 4th - Include VM profiles config
if profiles_config is None:
# Load profiles configuration from the provided file
profiles_config = vm_profiles_config(profiles_config_path,
providers_config)
opts['profiles'] = profiles_config
# recurse opts for sdb configs
apply_sdb(opts)
# prepend root_dir
prepend_root_dirs = ['cachedir']
if 'log_file' in opts and urlparse(opts['log_file']).scheme == '':
prepend_root_dirs.append(opts['log_file'])
prepend_root_dir(opts, prepend_root_dirs)
# Return the final options
return opts
def apply_cloud_config(overrides, defaults=None):
'''
Return a cloud config
'''
if defaults is None:
defaults = DEFAULT_CLOUD_OPTS.copy()
config = defaults.copy()
if overrides:
config.update(overrides)
# If the user defined providers in salt cloud's main configuration file, we
# need to take care for proper and expected format.
if 'providers' in config:
# Keep a copy of the defined providers
providers = config['providers'].copy()
# Reset the providers dictionary
config['providers'] = {}
# Populate the providers dictionary
for alias, details in six.iteritems(providers):
if isinstance(details, list):
for detail in details:
if 'driver' not in detail:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\'.'.format(
alias
)
)
driver = detail['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
detail['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = detail
elif isinstance(details, dict):
if 'driver' not in details:
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has an entry '
'missing the required setting of \'driver\''.format(
alias
)
)
driver = details['driver']
if ':' in driver:
# Weird, but...
alias, driver = driver.split(':')
if alias not in config['providers']:
config['providers'][alias] = {}
details['provider'] = '{0}:{1}'.format(alias, driver)
config['providers'][alias][driver] = details
# Migrate old configuration
config = old_to_new(config)
return config
def old_to_new(opts):
providers = (
'AWS',
'CLOUDSTACK',
'DIGITALOCEAN',
'EC2',
'GOGRID',
'IBMSCE',
'JOYENT',
'LINODE',
'OPENSTACK',
'PARALLELS'
'RACKSPACE',
'SALTIFY'
)
for provider in providers:
provider_config = {}
for opt, val in opts.items():
if provider in opt:
value = val
name = opt.split('.', 1)[1]
provider_config[name] = value
lprovider = provider.lower()
if provider_config:
provider_config['provider'] = lprovider
opts.setdefault('providers', {})
# provider alias
opts['providers'][lprovider] = {}
# provider alias, provider driver
opts['providers'][lprovider][lprovider] = provider_config
return opts
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.profiles')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_vm_profiles_config(providers, overrides, defaults)
def apply_vm_profiles_config(providers, overrides, defaults=None):
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
vms = {}
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, dict):
raise salt.exceptions.SaltCloudConfigError(
'The VM profiles configuration found in \'{0[conf_file]}\' is '
'not in the proper format'.format(config)
)
val['profile'] = key
vms[key] = val
# Is any VM profile extending data!?
for profile, details in six.iteritems(vms.copy()):
if 'extends' not in details:
if ':' in details['provider']:
alias, driver = details['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' '
'as the provider. Since there is no valid '
'configuration for that provider, the profile will be '
'removed from the available listing',
profile, details['provider']
)
vms.pop(profile)
continue
if 'profiles' not in providers[alias][driver]:
providers[alias][driver]['profiles'] = {}
providers[alias][driver]['profiles'][profile] = details
if details['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, details['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[details['provider']].keys())))
providers[details['provider']][driver].setdefault(
'profiles', {}).update({profile: details})
details['provider'] = '{0[provider]}:{1}'.format(details, driver)
vms[profile] = details
continue
extends = details.pop('extends')
if extends not in vms:
log.error(
'The \'%s\' profile is trying to extend data from \'%s\' '
'though \'%s\' is not defined in the salt profiles loaded '
'data. Not extending and removing from listing!',
profile, extends, extends
)
vms.pop(profile)
continue
extended = deepcopy(vms.get(extends))
extended.pop('profile')
# Merge extended configuration with base profile
extended = salt.utils.dictupdate.update(extended, details)
if ':' not in extended['provider']:
if extended['provider'] not in providers:
log.trace(
'The profile \'%s\' is defining \'%s\' as the '
'provider. Since there is no valid configuration for '
'that provider, the profile will be removed from the '
'available listing', profile, extended['provider']
)
vms.pop(profile)
continue
driver = next(iter(list(providers[extended['provider']].keys())))
providers[extended['provider']][driver].setdefault(
'profiles', {}).update({profile: extended})
extended['provider'] = '{0[provider]}:{1}'.format(extended, driver)
else:
alias, driver = extended['provider'].split(':')
if alias not in providers or driver not in providers[alias]:
log.trace(
'The profile \'%s\' is defining \'%s\' as '
'the provider. Since there is no valid configuration '
'for that provider, the profile will be removed from '
'the available listing', profile, extended['provider']
)
vms.pop(profile)
continue
providers[alias][driver].setdefault('profiles', {}).update(
{profile: extended}
)
# Update the profile's entry with the extended data
vms[profile] = extended
return vms
def cloud_providers_config(path,
env_var='SALT_CLOUD_PROVIDERS_CONFIG',
defaults=None):
'''
Read in the salt cloud providers configuration file
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
overrides = salt.config.load_config(
path, env_var, os.path.join(salt.syspaths.CONFIG_DIR, 'cloud.providers')
)
default_include = overrides.get(
'default_include', defaults['default_include']
)
include = overrides.get('include', [])
overrides.update(
salt.config.include_config(default_include, path, verbose=False)
)
overrides.update(
salt.config.include_config(include, path, verbose=True)
)
return apply_cloud_providers_config(overrides, defaults)
def apply_cloud_providers_config(overrides, defaults=None):
'''
Apply the loaded cloud providers configuration.
'''
if defaults is None:
defaults = PROVIDER_CONFIG_DEFAULTS
config = defaults.copy()
if overrides:
config.update(overrides)
# Is the user still using the old format in the new configuration file?!
for name, settings in six.iteritems(config.copy()):
if '.' in name:
log.warning(
'Please switch to the new providers configuration syntax'
)
# Let's help out and migrate the data
config = old_to_new(config)
# old_to_new will migrate the old data into the 'providers' key of
# the config dictionary. Let's map it correctly
for prov_name, prov_settings in six.iteritems(config.pop('providers')):
config[prov_name] = prov_settings
break
providers = {}
ext_count = 0
for key, val in six.iteritems(config):
if key in ('conf_file', 'include', 'default_include', 'user'):
continue
if not isinstance(val, (list, tuple)):
val = [val]
else:
# Need to check for duplicate cloud provider entries per "alias" or
# we won't be able to properly reference it.
handled_providers = set()
for details in val:
if 'driver' not in details:
if 'extends' not in details:
log.error(
'Please check your cloud providers configuration. '
'There\'s no \'driver\' nor \'extends\' definition '
'referenced.'
)
continue
if details['driver'] in handled_providers:
log.error(
'You can only have one entry per cloud provider. For '
'example, if you have a cloud provider configuration '
'section named, \'production\', you can only have a '
'single entry for EC2, Joyent, Openstack, and so '
'forth.'
)
raise salt.exceptions.SaltCloudConfigError(
'The cloud provider alias \'{0}\' has multiple entries '
'for the \'{1[driver]}\' driver.'.format(key, details)
)
handled_providers.add(details['driver'])
for entry in val:
if 'driver' not in entry:
entry['driver'] = '-only-extendable-{0}'.format(ext_count)
ext_count += 1
if key not in providers:
providers[key] = {}
provider = entry['driver']
if provider not in providers[key]:
providers[key][provider] = entry
# Is any provider extending data!?
while True:
keep_looping = False
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
# Set a holder for the defined profiles
providers[provider_alias][driver]['profiles'] = {}
if 'extends' not in details:
continue
extends = details.pop('extends')
if ':' in extends:
alias, provider = extends.split(':')
if alias not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though '
'\'{2}\' is not defined in the salt cloud '
'providers loaded data.'.format(
details['driver'],
provider_alias,
alias
)
)
if provider not in providers.get(alias):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}:{3}\' though '
'\'{3}\' is not defined in \'{1}\''.format(
details['driver'],
provider_alias,
alias,
provider
)
)
details['extends'] = '{0}:{1}'.format(alias, provider)
# change provider details '-only-extendable-' to extended
# provider name
details['driver'] = provider
elif providers.get(extends):
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend from \'{2}\' and no provider was '
'specified. Not extending!'.format(
details['driver'], provider_alias, extends
)
)
elif extends not in providers:
raise salt.exceptions.SaltCloudConfigError(
'The \'{0}\' cloud provider entry in \'{1}\' is '
'trying to extend data from \'{2}\' though \'{2}\' '
'is not defined in the salt cloud providers loaded '
'data.'.format(
details['driver'], provider_alias, extends
)
)
else:
if driver in providers.get(extends):
details['extends'] = '{0}:{1}'.format(extends, driver)
elif '-only-extendable-' in providers.get(extends):
details['extends'] = '{0}:{1}'.format(
extends, '-only-extendable-{0}'.format(ext_count)
)
else:
# We're still not aware of what we're trying to extend
# from. Let's try on next iteration
details['extends'] = extends
keep_looping = True
if not keep_looping:
break
while True:
# Merge provided extends
keep_looping = False
for alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries):
if 'extends' not in details:
# Extends resolved or non existing, continue!
continue
if 'extends' in details['extends']:
# Since there's a nested extends, resolve this one in the
# next iteration
keep_looping = True
continue
# Let's get a reference to what we're supposed to extend
extends = details.pop('extends')
# Split the setting in (alias, driver)
ext_alias, ext_driver = extends.split(':')
# Grab a copy of what should be extended
extended = providers.get(ext_alias).get(ext_driver).copy()
# Merge the data to extend with the details
extended = salt.utils.dictupdate.update(extended, details)
# Update the providers dictionary with the merged data
providers[alias][driver] = extended
# Update name of the driver, now that it's populated with extended information
if driver.startswith('-only-extendable-'):
providers[alias][ext_driver] = providers[alias][driver]
# Delete driver with old name to maintain dictionary size
del providers[alias][driver]
if not keep_looping:
break
# Now clean up any providers entry that was just used to be a data tree to
# extend from
for provider_alias, entries in six.iteritems(providers.copy()):
for driver, details in six.iteritems(entries.copy()):
if not driver.startswith('-only-extendable-'):
continue
log.info(
"There's at least one cloud driver under the '%s' "
'cloud provider alias which does not have the required '
"'driver' setting. Removing it from the available "
'providers listing.', provider_alias
)
providers[provider_alias].pop(driver)
if not providers[provider_alias]:
providers.pop(provider_alias)
return providers
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):
'''
Search and return a setting in a known order:
1. In the virtual machine's configuration
2. In the virtual machine's profile configuration
3. In the virtual machine's provider configuration
4. In the salt cloud configuration if global searching is enabled
5. Return the provided default
'''
# As a last resort, return the default
value = default
if search_global is True and opts.get(name, None) is not None:
# The setting name exists in the cloud(global) configuration
value = deepcopy(opts[name])
if vm_ and name:
# Let's get the value from the profile, if present
if 'profile' in vm_ and vm_['profile'] is not None:
if name in opts['profiles'][vm_['profile']]:
if isinstance(value, dict):
value.update(opts['profiles'][vm_['profile']][name].copy())
else:
value = deepcopy(opts['profiles'][vm_['profile']][name])
# Let's get the value from the provider, if present.
if ':' in vm_['driver']:
# The provider is defined as <provider-alias>:<driver-name>
alias, driver = vm_['driver'].split(':')
if alias in opts['providers'] and \
driver in opts['providers'][alias]:
details = opts['providers'][alias][driver]
if name in details:
if isinstance(value, dict):
value.update(details[name].copy())
else:
value = deepcopy(details[name])
elif len(opts['providers'].get(vm_['driver'], ())) > 1:
# The provider is NOT defined as <provider-alias>:<driver-name>
# and there's more than one entry under the alias.
# WARN the user!!!!
log.error(
"The '%s' cloud provider definition has more than one "
'entry. Your VM configuration should be specifying the '
"provider as 'driver: %s:<driver-engine>'. Since "
"it's not, we're returning the first definition which "
'might not be what you intended.',
vm_['driver'], vm_['driver']
)
if vm_['driver'] in opts['providers']:
# There's only one driver defined for this provider. This is safe.
alias_defs = opts['providers'].get(vm_['driver'])
provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]
if name in provider_driver_defs:
# The setting name exists in the VM's provider configuration.
# Return it!
if isinstance(value, dict):
value.update(provider_driver_defs[name].copy())
else:
value = deepcopy(provider_driver_defs[name])
if name and vm_ and name in vm_:
# The setting name exists in VM configuration.
if isinstance(vm_[name], types.GeneratorType):
value = next(vm_[name], '')
else:
if isinstance(value, dict) and isinstance(vm_[name], dict):
value.update(vm_[name].copy())
else:
value = deepcopy(vm_[name])
return value
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):
'''
Check and return the first matching and fully configured cloud provider
configuration.
'''
if ':' in provider:
alias, driver = provider.split(':')
if alias not in opts['providers']:
return False
if driver not in opts['providers'][alias]:
return False
for key in required_keys:
if opts['providers'][alias][driver].get(key, None) is None:
if log_message is True:
# There's at least one require configuration key which is not
# set.
log.warning(
"The required '%s' configuration setting is missing "
"from the '%s' driver, which is configured under the "
"'%s' alias.", key, provider, alias
)
return False
# If we reached this far, there's a properly configured provider.
# Return it!
return opts['providers'][alias][driver]
for alias, drivers in six.iteritems(opts['providers']):
for driver, provider_details in six.iteritems(drivers):
if driver != provider and driver not in aliases:
continue
# If we reached this far, we have a matching provider, let's see if
# all required configuration keys are present and not None.
skip_provider = False
for key in required_keys:
if provider_details.get(key, None) is None:
if log_message is True:
# This provider does not include all necessary keys,
# continue to next one.
log.warning(
"The required '%s' configuration setting is "
"missing from the '%s' driver, which is configured "
"under the '%s' alias.", key, provider, alias
)
skip_provider = True
break
if skip_provider:
continue
# If we reached this far, the provider included all required keys
return provider_details
# If we reached this point, the provider is not configured.
return False
def is_profile_configured(opts, provider, profile_name, vm_=None):
'''
Check if the requested profile contains the minimum required parameters for
a profile.
Required parameters include image and provider for all drivers, while some
drivers also require size keys.
.. versionadded:: 2015.8.0
'''
# Standard dict keys required by all drivers.
required_keys = ['provider']
alias, driver = provider.split(':')
# Most drivers need an image to be specified, but some do not.
non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']
# Most drivers need a size, but some do not.
non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
'virtualbox', 'libvirt', 'oneandone', 'profitbricks']
provider_key = opts['providers'][alias][driver]
profile_key = opts['providers'][alias][driver]['profiles'][profile_name]
# If cloning on Linode, size and image are not necessary.
# They are obtained from the to-be-cloned VM.
if driver == 'linode' and profile_key.get('clonefrom', False):
non_image_drivers.append('linode')
non_size_drivers.append('linode')
elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
non_image_drivers.append('gce')
# If cloning on VMware, specifying image is not necessary.
if driver == 'vmware' and 'image' not in list(profile_key.keys()):
non_image_drivers.append('vmware')
if driver not in non_image_drivers:
required_keys.append('image')
if driver == 'vmware':
required_keys.append('datastore')
elif driver in ['linode', 'virtualbox']:
required_keys.append('clonefrom')
elif driver == 'nova':
nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
required_keys.extend(nova_image_keys)
if driver not in non_size_drivers:
required_keys.append('size')
# Check if required fields are supplied in the provider config. If they
# are present, remove it from the required_keys list.
for item in list(required_keys):
if item in provider_key:
required_keys.remove(item)
# If a vm_ dict was passed in, use that information to get any other configs
# that we might have missed thus far, such as a option provided in a map file.
if vm_:
for item in list(required_keys):
if item in vm_:
required_keys.remove(item)
# Check for remaining required parameters in the profile config.
for item in required_keys:
if profile_key.get(item, None) is None:
# There's at least one required configuration item which is not set.
log.error(
"The required '%s' configuration setting is missing from "
"the '%s' profile, which is configured under the '%s' alias.",
item, profile_name, alias
)
return False
return True
def check_driver_dependencies(driver, dependencies):
'''
Check if the driver's dependencies are available.
.. versionadded:: 2015.8.0
driver
The name of the driver.
dependencies
The dictionary of dependencies to check.
'''
ret = True
for key, value in six.iteritems(dependencies):
if value is False:
log.warning(
"Missing dependency: '%s'. The %s driver requires "
"'%s' to be installed.", key, driver, key
)
ret = False
return ret
# <---- Salt Cloud Configuration Functions -----------------------------------
def _cache_id(minion_id, cache_file):
'''
Helper function, writes minion id to a cache file.
'''
path = os.path.dirname(cache_file)
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exc:
# Handle race condition where dir is created after os.path.isdir check
if os.path.isdir(path):
pass
else:
log.error('Failed to create dirs to minion_id file: %s', exc)
try:
with salt.utils.files.fopen(cache_file, 'w') as idf:
idf.write(minion_id)
except (IOError, OSError) as exc:
log.error('Could not cache minion ID: %s', exc)
def call_id_function(opts):
'''
Evaluate the function that determines the ID if the 'id_function'
option is set and return the result
'''
if opts.get('id'):
return opts['id']
# Import 'salt.loader' here to avoid a circular dependency
import salt.loader as loader
if isinstance(opts['id_function'], six.string_types):
mod_fun = opts['id_function']
fun_kwargs = {}
elif isinstance(opts['id_function'], dict):
mod_fun, fun_kwargs = six.next(six.iteritems(opts['id_function']))
if fun_kwargs is None:
fun_kwargs = {}
else:
log.error('\'id_function\' option is neither a string nor a dictionary')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# split module and function and try loading the module
mod, fun = mod_fun.split('.')
if not opts.get('grains'):
# Get grains for use by the module
opts['grains'] = loader.grains(opts)
try:
id_mod = loader.raw_mod(opts, mod, fun)
if not id_mod:
raise KeyError
# we take whatever the module returns as the minion ID
newid = id_mod[mod_fun](**fun_kwargs)
if not isinstance(newid, six.string_types) or not newid:
log.error(
'Function %s returned value "%s" of type %s instead of string',
mod_fun, newid, type(newid)
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated minion ID from module: %s', mod_fun)
return newid
except TypeError:
log.error(
'Function arguments %s are incorrect for function %s',
fun_kwargs, mod_fun
)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
def remove_domain_from_fqdn(opts, newid):
'''
Depending on the values of `minion_id_remove_domain`,
remove all domains or a single domain from a FQDN, effectivly generating a hostname.
'''
opt_domain = opts.get('minion_id_remove_domain')
if opt_domain is True:
if '.' in newid:
# Remove any domain
newid, xdomain = newid.split('.', 1)
log.debug('Removed any domain (%s) from minion id.', xdomain)
else:
# Must be string type
if newid.upper().endswith('.' + opt_domain.upper()):
# Remove single domain
newid = newid[:-len('.' + opt_domain)]
log.debug('Removed single domain %s from minion id.', opt_domain)
return newid
def get_id(opts, cache_minion_id=False):
'''
Guess the id of the minion.
If CONFIG_DIR/minion_id exists, use the cached minion ID from that file.
If no minion id is configured, use multiple sources to find a FQDN.
If no FQDN is found you may get an ip address.
Returns two values: the detected ID, and a boolean value noting whether or
not an IP address is being used for the ID.
'''
if opts['root_dir'] is None:
root_dir = salt.syspaths.ROOT_DIR
else:
root_dir = opts['root_dir']
config_dir = salt.syspaths.CONFIG_DIR
if config_dir.startswith(salt.syspaths.ROOT_DIR):
config_dir = config_dir.split(salt.syspaths.ROOT_DIR, 1)[-1]
# Check for cached minion ID
id_cache = os.path.join(root_dir,
config_dir.lstrip(os.path.sep),
'minion_id')
if opts.get('minion_id_caching', True):
try:
with salt.utils.files.fopen(id_cache) as idf:
name = salt.utils.stringutils.to_unicode(idf.readline().strip())
bname = salt.utils.stringutils.to_bytes(name)
if bname.startswith(codecs.BOM): # Remove BOM if exists
name = salt.utils.stringutils.to_str(bname.replace(codecs.BOM, '', 1))
if name and name != 'localhost':
log.debug('Using cached minion ID from %s: %s', id_cache, name)
return name, False
except (IOError, OSError):
pass
if '__role' in opts and opts.get('__role') == 'minion':
log.debug(
'Guessing ID. The id can be explicitly set in %s',
os.path.join(salt.syspaths.CONFIG_DIR, 'minion')
)
if opts.get('id_function'):
newid = call_id_function(opts)
else:
newid = salt.utils.network.generate_minion_id()
if opts.get('minion_id_lowercase'):
newid = newid.lower()
log.debug('Changed minion id %s to lowercase.', newid)
# Optionally remove one or many domains in a generated minion id
if opts.get('minion_id_remove_domain'):
newid = remove_domain_from_fqdn(opts, newid)
if '__role' in opts and opts.get('__role') == 'minion':
if opts.get('id_function'):
log.debug(
'Found minion id from external function %s: %s',
opts['id_function'], newid
)
else:
log.debug('Found minion id from generate_minion_id(): %s', newid)
if cache_minion_id and opts.get('minion_id_caching', True):
_cache_id(newid, id_cache)
is_ipv4 = salt.utils.network.is_ipv4(newid)
return newid, is_ipv4
def _update_ssl_config(opts):
'''
Resolves string names to integer constant in ssl configuration.
'''
if opts['ssl'] in (None, False):
opts['ssl'] = None
return
if opts['ssl'] is True:
opts['ssl'] = {}
return
import ssl
for key, prefix in (('cert_reqs', 'CERT_'),
('ssl_version', 'PROTOCOL_')):
val = opts['ssl'].get(key)
if val is None:
continue
if not isinstance(val, six.string_types) or not val.startswith(prefix) or not hasattr(ssl, val):
message = 'SSL option \'{0}\' must be set to one of the following values: \'{1}\'.' \
.format(key, '\', \''.join([val for val in dir(ssl) if val.startswith(prefix)]))
log.error(message)
raise salt.exceptions.SaltConfigurationError(message)
opts['ssl'][key] = getattr(ssl, val)
def _adjust_log_file_override(overrides, default_log_file):
'''
Adjusts the log_file based on the log_dir override
'''
if overrides.get('log_dir'):
# Adjust log_file if a log_dir override is introduced
if overrides.get('log_file'):
if not os.path.isabs(overrides['log_file']):
# Prepend log_dir if log_file is relative
overrides['log_file'] = os.path.join(overrides['log_dir'],
overrides['log_file'])
else:
# Create the log_file override
overrides['log_file'] = \
os.path.join(overrides['log_dir'],
os.path.basename(default_log_file))
def apply_minion_config(overrides=None,
defaults=None,
cache_minion_id=False,
minion_id=None):
'''
Returns minion configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MINION_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'minion'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' minion config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom module is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' minion config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in minion opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
# No ID provided. Will getfqdn save us?
using_ip_for_id = False
if not opts.get('id'):
if minion_id:
opts['id'] = minion_id
else:
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=cache_minion_id)
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
for directory in opts.get('append_minionid_config_dirs', []):
if directory in ('pki_dir', 'cachedir', 'extension_modules'):
newdirectory = os.path.join(opts[directory], opts['id'])
opts[directory] = newdirectory
elif directory == 'default_include' and directory in opts:
include_dir = os.path.dirname(opts[directory])
new_include_dir = os.path.join(include_dir,
opts['id'],
os.path.basename(opts[directory]))
opts[directory] = new_include_dir
# pidfile can be in the list of append_minionid_config_dirs, but pidfile
# is the actual path with the filename, not a directory.
if 'pidfile' in opts.get('append_minionid_config_dirs', []):
newpath_list = os.path.split(opts['pidfile'])
opts['pidfile'] = os.path.join(newpath_list[0], 'salt', opts['id'], newpath_list[1])
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_pillar_roots(opts['pillar_roots'])
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'sock_dir', 'extension_modules', 'pidfile',
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile'):
if urlparse(opts.get(config_key, '')).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# if there is no beacons option yet, add an empty beacons dict
if 'beacons' not in opts:
opts['beacons'] = {}
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def _update_discovery_config(opts):
'''
Update discovery config for all instances.
:param opts:
:return:
'''
if opts.get('discovery') not in (None, False):
if opts['discovery'] is True:
opts['discovery'] = {}
discovery_config = {'attempts': 3, 'pause': 5, 'port': 4520, 'match': 'any', 'mapping': {}, 'multimaster': False}
for key in opts['discovery']:
if key not in discovery_config:
raise salt.exceptions.SaltConfigurationError('Unknown discovery option: {0}'.format(key))
if opts.get('__role') != 'minion':
for key in ['attempts', 'pause', 'match']:
del discovery_config[key]
opts['discovery'] = salt.utils.dictupdate.update(discovery_config, opts['discovery'], True, True)
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):
'''
Reads in the master configuration file and sets up default options
This is useful for running the actual master daemon. For running
Master-side client interfaces that need the master opts see
:py:func:`salt.client.client_config`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if not os.environ.get(env_var, None):
# No valid setting was given using the configuration variable.
# Lets see is SALT_CONFIG_DIR is of any use
salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)
if salt_config_dir:
env_config_file_path = os.path.join(salt_config_dir, 'master')
if salt_config_dir and os.path.isfile(env_config_file_path):
# We can get a configuration file using SALT_CONFIG_DIR, let's
# update the environment with this information
os.environ[env_var] = env_config_file_path
overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])
default_include = overrides.get('default_include',
defaults['default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False,
exit_on_config_errors=exit_on_config_errors))
overrides.update(include_config(include, path, verbose=True,
exit_on_config_errors=exit_on_config_errors))
opts = apply_master_config(overrides, defaults)
_validate_ssh_minion_opts(opts)
_validate_opts(opts)
# If 'nodegroups:' is uncommented in the master config file, and there are
# no nodegroups defined, opts['nodegroups'] will be None. Fix this by
# reverting this value to the default, as if 'nodegroups:' was commented
# out or not present.
if opts.get('nodegroups') is None:
opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})
if salt.utils.data.is_dictlist(opts['nodegroups']):
opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])
apply_sdb(opts)
return opts
def apply_master_config(overrides=None, defaults=None):
'''
Returns master configurations dict.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
if overrides is None:
overrides = {}
opts = defaults.copy()
opts['__role'] = 'master'
_adjust_log_file_override(overrides, defaults['log_file'])
if overrides:
opts.update(overrides)
opts['__cli'] = salt.utils.stringutils.to_unicode(
os.path.basename(sys.argv[0])
)
if 'environment' in opts:
if opts['saltenv'] is not None:
log.warning(
'The \'saltenv\' and \'environment\' master config options '
'cannot both be used. Ignoring \'environment\' in favor of '
'\'saltenv\'.',
)
# Set environment to saltenv in case someone's custom runner is
# refrencing __opts__['environment']
opts['environment'] = opts['saltenv']
else:
log.warning(
'The \'environment\' master config option has been renamed '
'to \'saltenv\'. Using %s as the \'saltenv\' config value.',
opts['environment']
)
opts['saltenv'] = opts['environment']
if six.PY2 and 'rest_cherrypy' in opts:
# CherryPy is not unicode-compatible
opts['rest_cherrypy'] = salt.utils.data.encode(opts['rest_cherrypy'])
for idx, val in enumerate(opts['fileserver_backend']):
if val in ('git', 'hg', 'svn', 'minion'):
new_val = val + 'fs'
log.debug(
'Changed %s to %s in master opts\' fileserver_backend list',
val, new_val
)
opts['fileserver_backend'][idx] = new_val
if len(opts['sock_dir']) > len(opts['cachedir']) + 10:
opts['sock_dir'] = os.path.join(opts['cachedir'], '.salt-unix')
opts['token_dir'] = os.path.join(opts['cachedir'], 'tokens')
opts['syndic_dir'] = os.path.join(opts['cachedir'], 'syndics')
# Make sure ext_mods gets set if it is an untrue value
# (here to catch older bad configs)
opts['extension_modules'] = (
opts.get('extension_modules') or
os.path.join(opts['cachedir'], 'extmods')
)
# Set up the utils_dirs location from the extension_modules location
opts['utils_dirs'] = (
opts.get('utils_dirs') or
[os.path.join(opts['extension_modules'], 'utils')]
)
# Insert all 'utils_dirs' directories to the system path
insert_system_path(opts, opts['utils_dirs'])
if overrides.get('ipc_write_buffer', '') == 'dynamic':
opts['ipc_write_buffer'] = _DFLT_IPC_WBUFFER
using_ip_for_id = False
append_master = False
if not opts.get('id'):
opts['id'], using_ip_for_id = get_id(
opts,
cache_minion_id=None)
append_master = True
# it does not make sense to append a domain to an IP based id
if not using_ip_for_id and 'append_domain' in opts:
opts['id'] = _append_domain(opts)
if append_master:
opts['id'] += '_master'
# Prepend root_dir to other paths
prepend_root_dirs = [
'pki_dir', 'cachedir', 'pidfile', 'sock_dir', 'extension_modules',
'autosign_file', 'autoreject_file', 'token_dir', 'syndic_dir',
'sqlite_queue_dir', 'autosign_grains_dir'
]
# These can be set to syslog, so, not actual paths on the system
for config_key in ('log_file', 'key_logfile', 'ssh_log_file'):
log_setting = opts.get(config_key, '')
if log_setting is None:
continue
if urlparse(log_setting).scheme == '':
prepend_root_dirs.append(config_key)
prepend_root_dir(opts, prepend_root_dirs)
# Enabling open mode requires that the value be set to True, and
# nothing else!
opts['open_mode'] = opts['open_mode'] is True
opts['auto_accept'] = opts['auto_accept'] is True
opts['file_roots'] = _validate_file_roots(opts['file_roots'])
opts['pillar_roots'] = _validate_file_roots(opts['pillar_roots'])
if opts['file_ignore_regex']:
# If file_ignore_regex was given, make sure it's wrapped in a list.
# Only keep valid regex entries for improved performance later on.
if isinstance(opts['file_ignore_regex'], six.string_types):
ignore_regex = [opts['file_ignore_regex']]
elif isinstance(opts['file_ignore_regex'], list):
ignore_regex = opts['file_ignore_regex']
opts['file_ignore_regex'] = []
for regex in ignore_regex:
try:
# Can't store compiled regex itself in opts (breaks
# serialization)
re.compile(regex)
opts['file_ignore_regex'].append(regex)
except Exception:
log.warning(
'Unable to parse file_ignore_regex. Skipping: %s',
regex
)
if opts['file_ignore_glob']:
# If file_ignore_glob was given, make sure it's wrapped in a list.
if isinstance(opts['file_ignore_glob'], six.string_types):
opts['file_ignore_glob'] = [opts['file_ignore_glob']]
# Let's make sure `worker_threads` does not drop below 3 which has proven
# to make `salt.modules.publish` not work under the test-suite.
if opts['worker_threads'] < 3 and opts.get('peer', None):
log.warning(
"The 'worker_threads' setting in '%s' cannot be lower than "
'3. Resetting it to the default value of 3.', opts['conf_file']
)
opts['worker_threads'] = 3
opts.setdefault('pillar_source_merging_strategy', 'smart')
# Make sure hash_type is lowercase
opts['hash_type'] = opts['hash_type'].lower()
# Check and update TLS/SSL configuration
_update_ssl_config(opts)
_update_discovery_config(opts)
return opts
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):
'''
Load Master configuration data
Usage:
.. code-block:: python
import salt.config
master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary
options needed to communicate with a locally-running Salt Master daemon.
This function searches for client specific configurations and adds them to
the data from the master configuration.
This is useful for master-side operations like
:py:class:`~salt.client.LocalClient`.
'''
if defaults is None:
defaults = DEFAULT_MASTER_OPTS.copy()
xdg_dir = salt.utils.xdg.xdg_config_dir()
if os.path.isdir(xdg_dir):
client_config_dir = xdg_dir
saltrc_config_file = 'saltrc'
else:
client_config_dir = os.path.expanduser('~')
saltrc_config_file = '.saltrc'
# Get the token file path from the provided defaults. If not found, specify
# our own, sane, default
opts = {
'token_file': defaults.get(
'token_file',
os.path.join(client_config_dir, 'salt_token')
)
}
# Update options with the master configuration, either from the provided
# path, salt's defaults or provided defaults
opts.update(
master_config(path, defaults=defaults)
)
# Update with the users salt dot file or with the environment variable
saltrc_config = os.path.join(client_config_dir, saltrc_config_file)
opts.update(
load_config(
saltrc_config,
env_var,
saltrc_config
)
)
# Make sure we have a proper and absolute path to the token file
if 'token_file' in opts:
opts['token_file'] = os.path.abspath(
os.path.expanduser(
opts['token_file']
)
)
# If the token file exists, read and store the contained token
if os.path.isfile(opts['token_file']):
# Make sure token is still valid
expire = opts.get('token_expire', 43200)
if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):
with salt.utils.files.fopen(opts['token_file']) as fp_:
opts['token'] = fp_.read().strip()
# On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost
if opts['interface'] == '0.0.0.0':
opts['interface'] = '127.0.0.1'
# Make sure the master_uri is set
if 'master_uri' not in opts:
opts['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(opts['interface']),
port=opts['ret_port']
)
# Return the client options
_validate_opts(opts)
return opts
def api_config(path):
'''
Read in the Salt Master config file and add additional configs that
need to be stubbed out for salt-api
'''
# Let's grab a copy of salt-api's required defaults
opts = DEFAULT_API_OPTS.copy()
# Let's override them with salt's master opts
opts.update(client_config(path, defaults=DEFAULT_MASTER_OPTS.copy()))
# Let's set the pidfile and log_file values in opts to api settings
opts.update({
'pidfile': opts.get('api_pidfile', DEFAULT_API_OPTS['api_pidfile']),
'log_file': opts.get('api_logfile', DEFAULT_API_OPTS['api_logfile']),
})
prepend_root_dir(opts, [
'api_pidfile',
'api_logfile',
'log_file',
'pidfile'
])
return opts
def spm_config(path):
'''
Read in the salt master config file and add additional configs that
need to be stubbed out for spm
.. versionadded:: 2015.8.0
'''
# Let's grab a copy of salt's master default opts
defaults = DEFAULT_MASTER_OPTS.copy()
# Let's override them with spm's required defaults
defaults.update(DEFAULT_SPM_OPTS)
overrides = load_config(path, 'SPM_CONFIG', DEFAULT_SPM_OPTS['spm_conf_file'])
default_include = overrides.get('spm_default_include',
defaults['spm_default_include'])
include = overrides.get('include', [])
overrides.update(include_config(default_include, path, verbose=False))
overrides.update(include_config(include, path, verbose=True))
defaults = apply_master_config(overrides, defaults)
defaults = apply_spm_config(overrides, defaults)
return client_config(path, env_var='SPM_CONFIG', defaults=defaults)
|
saltstack/salt
|
salt/pillar/pillar_ldap.py
|
_render_template
|
python
|
def _render_template(config_file):
'''
Render config template, substituting grains where found.
'''
dirname, filename = os.path.split(config_file)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname))
template = env.get_template(filename)
return template.render(__grains__)
|
Render config template, substituting grains where found.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L156-L163
| null |
# -*- coding: utf-8 -*-
'''
Use LDAP data as a Pillar source
This pillar module executes a series of LDAP searches.
Data returned by these searches are aggregated, whereby data returned by later
searches override data by previous searches with the same key.
The final result is merged with existing pillar data.
The configuration of this external pillar module is done via an external
file which provides the actual configuration for the LDAP searches.
===============================
Configuring the LDAP ext_pillar
===============================
The basic configuration is part of the `master configuration
<master-configuration-ext-pillar>`_.
.. code-block:: yaml
ext_pillar:
- pillar_ldap: /etc/salt/master.d/pillar_ldap.yaml
.. note::
When placing the file in the ``master.d`` directory, make sure its name
doesn't end in ``.conf``, otherwise the salt-master process will attempt
to parse its content.
.. warning::
Make sure this file has very restrictive permissions, as it will contain
possibly sensitive LDAP credentials!
The only required key in the master configuration is ``pillar_ldap`` pointing
to a file containing the actual configuration.
Configuring the LDAP searches
=============================
The file is processed using `Salt's Renderers <renderers>` which makes it
possible to reference grains within the configuration.
.. warning::
When using Jinja in this file, make sure to do it in a way which prevents
leaking sensitive information. A rogue minion could send arbitrary grains
to trick the master into returning secret data.
Use only the 'id' grain which is verified through the minion's key/cert.
Map Mode
--------
The ``it-admins`` configuration below returns the Pillar ``it-admins`` by:
- filtering for:
- members of the group ``it-admins``
- objects with ``objectclass=user``
- returning the data of users, where each user is a dictionary containing the
configured string or list attributes.
Configuration
*************
.. code-block:: yaml
salt-users:
server: ldap.company.tld
port: 389
tls: true
dn: 'dc=company,dc=tld'
binddn: 'cn=salt-pillars,ou=users,dc=company,dc=tld'
bindpw: bi7ieBai5Ano
referrals: false
anonymous: false
mode: map
dn: 'ou=users,dc=company,dc=tld'
filter: '(&(memberof=cn=it-admins,ou=groups,dc=company,dc=tld)(objectclass=user))'
attrs:
- cn
- displayName
- givenName
- sn
lists:
- memberOf
search_order:
- salt-users
Result
******
.. code-block:: python
{
'salt-users': [
{
'cn': 'cn=johndoe,ou=users,dc=company,dc=tld',
'displayName': 'John Doe'
'givenName': 'John'
'sn': 'Doe'
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team01,ou=groups,dc=company'
]
},
{
'cn': 'cn=janedoe,ou=users,dc=company,dc=tld',
'displayName': 'Jane Doe',
'givenName': 'Jane',
'sn': 'Doe',
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team02,ou=groups,dc=company'
]
}
]
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import salt libs
import salt.utils.data
from salt.exceptions import SaltInvocationError
# Import third party libs
import jinja2
try:
import ldap # pylint: disable=W0611
HAS_LDAP = True
except ImportError:
HAS_LDAP = False
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if ldap module is installed
'''
if HAS_LDAP:
return 'pillar_ldap'
else:
return False
def _config(name, conf, default=None):
'''
Return a value for 'name' from the config file options. If the 'name' is
not in the config, the 'default' value is returned. This method converts
unicode values to str type under python 2.
'''
try:
value = conf[name]
except KeyError:
value = default
return salt.utils.data.decode(value, to_str=True)
def _result_to_dict(data, result, conf, source):
'''
Aggregates LDAP search result based on rules, returns a dictionary.
Rules:
Attributes tagged in the pillar config as 'attrs' or 'lists' are
scanned for a 'key=value' format (non matching entries are ignored.
Entries matching the 'attrs' tag overwrite previous values where
the key matches a previous result.
Entries matching the 'lists' tag are appended to list of values where
the key matches a previous result.
All Matching entries are then written directly to the pillar data
dictionary as data[key] = value.
For example, search result:
{ saltKeyValue': ['ntpserver=ntp.acme.local', 'foo=myfoo'],
'saltList': ['vhost=www.acme.net', 'vhost=www.acme.local'] }
is written to the pillar data dictionary as:
{ 'ntpserver': 'ntp.acme.local', 'foo': 'myfoo',
'vhost': ['www.acme.net', 'www.acme.local'] }
'''
attrs = _config('attrs', conf) or []
lists = _config('lists', conf) or []
dict_key_attr = _config('dict_key_attr', conf) or 'dn'
# TODO:
# deprecate the default 'mode: split' and make the more
# straightforward 'mode: map' the new default
mode = _config('mode', conf) or 'split'
if mode == 'map':
data[source] = []
for record in result:
ret = {}
if 'dn' in attrs or 'distinguishedName' in attrs:
log.debug('dn: %s', record[0])
ret['dn'] = record[0]
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
data[source].append(ret)
elif mode == 'dict':
data[source] = {}
for record in result:
ret = {}
distinguished_name = record[0]
log.debug('dn: %s', distinguished_name)
if 'dn' in attrs or 'distinguishedName' in attrs:
ret['dn'] = distinguished_name
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
if dict_key_attr in ['dn', 'distinguishedName']:
dict_key = distinguished_name
else:
dict_key = ','.join(sorted(record.get(dict_key_attr, [])))
try:
data[source][dict_key].append(ret)
except KeyError:
data[source][dict_key] = [ret]
elif mode == 'split':
for key in result[0][1]:
if key in attrs:
for item in result.get(key):
skey, sval = item.split('=', 1)
data[skey] = sval
elif key in lists:
for item in result.get(key):
if '=' in item:
skey, sval = item.split('=', 1)
if skey not in data:
data[skey] = [sval]
else:
data[skey].append(sval)
return data
def _do_search(conf):
'''
Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use.
'''
# Build LDAP connection args
connargs = {}
for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']:
connargs[name] = _config(name, conf)
if connargs['binddn'] and connargs['bindpw']:
connargs['anonymous'] = False
# Build search args
try:
_filter = conf['filter']
except KeyError:
raise SaltInvocationError('missing filter')
_dn = _config('dn', conf)
scope = _config('scope', conf)
_lists = _config('lists', conf) or []
_attrs = _config('attrs', conf) or []
_dict_key_attr = _config('dict_key_attr', conf, 'dn')
attrs = _lists + _attrs + [_dict_key_attr]
if not attrs:
attrs = None
# Perform the search
try:
result = __salt__['ldap.search'](_filter, _dn, scope, attrs,
**connargs)['results']
except IndexError: # we got no results for this search
log.debug('LDAP search returned no results for filter %s', _filter)
result = {}
except Exception:
log.critical(
'Failed to retrieve pillar data from LDAP:\n', exc_info=True
)
return {}
return result
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
config_file):
'''
Execute LDAP searches and return the aggregated data
'''
config_template = None
try:
config_template = _render_template(config_file)
except jinja2.exceptions.TemplateNotFound:
log.debug('pillar_ldap: missing configuration file %s', config_file)
except Exception:
log.debug('pillar_ldap: failed to render template for %s',
config_file, exc_info=True)
if not config_template:
# We don't have a config file
return {}
import salt.utils.yaml
try:
opts = salt.utils.yaml.safe_load(config_template) or {}
opts['conf_file'] = config_file
except Exception as err:
import salt.log
msg = 'pillar_ldap: error parsing configuration file: {0} - {1}'.format(
config_file, err
)
if salt.log.is_console_configured():
log.warning(msg)
else:
print(msg)
return {}
else:
if not isinstance(opts, dict):
log.warning(
'pillar_ldap: %s is invalidly formatted, must be a YAML '
'dictionary. See the documentation for more information.',
config_file
)
return {}
if 'search_order' not in opts:
log.warning(
'pillar_ldap: search_order missing from configuration. See the '
'documentation for more information.'
)
return {}
data = {}
for source in opts['search_order']:
config = opts[source]
result = _do_search(config)
log.debug('source %s got result %s', source, result)
if result:
data = _result_to_dict(data, result, config, source)
return data
|
saltstack/salt
|
salt/pillar/pillar_ldap.py
|
_config
|
python
|
def _config(name, conf, default=None):
'''
Return a value for 'name' from the config file options. If the 'name' is
not in the config, the 'default' value is returned. This method converts
unicode values to str type under python 2.
'''
try:
value = conf[name]
except KeyError:
value = default
return salt.utils.data.decode(value, to_str=True)
|
Return a value for 'name' from the config file options. If the 'name' is
not in the config, the 'default' value is returned. This method converts
unicode values to str type under python 2.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L166-L176
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n"
] |
# -*- coding: utf-8 -*-
'''
Use LDAP data as a Pillar source
This pillar module executes a series of LDAP searches.
Data returned by these searches are aggregated, whereby data returned by later
searches override data by previous searches with the same key.
The final result is merged with existing pillar data.
The configuration of this external pillar module is done via an external
file which provides the actual configuration for the LDAP searches.
===============================
Configuring the LDAP ext_pillar
===============================
The basic configuration is part of the `master configuration
<master-configuration-ext-pillar>`_.
.. code-block:: yaml
ext_pillar:
- pillar_ldap: /etc/salt/master.d/pillar_ldap.yaml
.. note::
When placing the file in the ``master.d`` directory, make sure its name
doesn't end in ``.conf``, otherwise the salt-master process will attempt
to parse its content.
.. warning::
Make sure this file has very restrictive permissions, as it will contain
possibly sensitive LDAP credentials!
The only required key in the master configuration is ``pillar_ldap`` pointing
to a file containing the actual configuration.
Configuring the LDAP searches
=============================
The file is processed using `Salt's Renderers <renderers>` which makes it
possible to reference grains within the configuration.
.. warning::
When using Jinja in this file, make sure to do it in a way which prevents
leaking sensitive information. A rogue minion could send arbitrary grains
to trick the master into returning secret data.
Use only the 'id' grain which is verified through the minion's key/cert.
Map Mode
--------
The ``it-admins`` configuration below returns the Pillar ``it-admins`` by:
- filtering for:
- members of the group ``it-admins``
- objects with ``objectclass=user``
- returning the data of users, where each user is a dictionary containing the
configured string or list attributes.
Configuration
*************
.. code-block:: yaml
salt-users:
server: ldap.company.tld
port: 389
tls: true
dn: 'dc=company,dc=tld'
binddn: 'cn=salt-pillars,ou=users,dc=company,dc=tld'
bindpw: bi7ieBai5Ano
referrals: false
anonymous: false
mode: map
dn: 'ou=users,dc=company,dc=tld'
filter: '(&(memberof=cn=it-admins,ou=groups,dc=company,dc=tld)(objectclass=user))'
attrs:
- cn
- displayName
- givenName
- sn
lists:
- memberOf
search_order:
- salt-users
Result
******
.. code-block:: python
{
'salt-users': [
{
'cn': 'cn=johndoe,ou=users,dc=company,dc=tld',
'displayName': 'John Doe'
'givenName': 'John'
'sn': 'Doe'
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team01,ou=groups,dc=company'
]
},
{
'cn': 'cn=janedoe,ou=users,dc=company,dc=tld',
'displayName': 'Jane Doe',
'givenName': 'Jane',
'sn': 'Doe',
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team02,ou=groups,dc=company'
]
}
]
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import salt libs
import salt.utils.data
from salt.exceptions import SaltInvocationError
# Import third party libs
import jinja2
try:
import ldap # pylint: disable=W0611
HAS_LDAP = True
except ImportError:
HAS_LDAP = False
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if ldap module is installed
'''
if HAS_LDAP:
return 'pillar_ldap'
else:
return False
def _render_template(config_file):
'''
Render config template, substituting grains where found.
'''
dirname, filename = os.path.split(config_file)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname))
template = env.get_template(filename)
return template.render(__grains__)
def _result_to_dict(data, result, conf, source):
'''
Aggregates LDAP search result based on rules, returns a dictionary.
Rules:
Attributes tagged in the pillar config as 'attrs' or 'lists' are
scanned for a 'key=value' format (non matching entries are ignored.
Entries matching the 'attrs' tag overwrite previous values where
the key matches a previous result.
Entries matching the 'lists' tag are appended to list of values where
the key matches a previous result.
All Matching entries are then written directly to the pillar data
dictionary as data[key] = value.
For example, search result:
{ saltKeyValue': ['ntpserver=ntp.acme.local', 'foo=myfoo'],
'saltList': ['vhost=www.acme.net', 'vhost=www.acme.local'] }
is written to the pillar data dictionary as:
{ 'ntpserver': 'ntp.acme.local', 'foo': 'myfoo',
'vhost': ['www.acme.net', 'www.acme.local'] }
'''
attrs = _config('attrs', conf) or []
lists = _config('lists', conf) or []
dict_key_attr = _config('dict_key_attr', conf) or 'dn'
# TODO:
# deprecate the default 'mode: split' and make the more
# straightforward 'mode: map' the new default
mode = _config('mode', conf) or 'split'
if mode == 'map':
data[source] = []
for record in result:
ret = {}
if 'dn' in attrs or 'distinguishedName' in attrs:
log.debug('dn: %s', record[0])
ret['dn'] = record[0]
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
data[source].append(ret)
elif mode == 'dict':
data[source] = {}
for record in result:
ret = {}
distinguished_name = record[0]
log.debug('dn: %s', distinguished_name)
if 'dn' in attrs or 'distinguishedName' in attrs:
ret['dn'] = distinguished_name
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
if dict_key_attr in ['dn', 'distinguishedName']:
dict_key = distinguished_name
else:
dict_key = ','.join(sorted(record.get(dict_key_attr, [])))
try:
data[source][dict_key].append(ret)
except KeyError:
data[source][dict_key] = [ret]
elif mode == 'split':
for key in result[0][1]:
if key in attrs:
for item in result.get(key):
skey, sval = item.split('=', 1)
data[skey] = sval
elif key in lists:
for item in result.get(key):
if '=' in item:
skey, sval = item.split('=', 1)
if skey not in data:
data[skey] = [sval]
else:
data[skey].append(sval)
return data
def _do_search(conf):
'''
Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use.
'''
# Build LDAP connection args
connargs = {}
for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']:
connargs[name] = _config(name, conf)
if connargs['binddn'] and connargs['bindpw']:
connargs['anonymous'] = False
# Build search args
try:
_filter = conf['filter']
except KeyError:
raise SaltInvocationError('missing filter')
_dn = _config('dn', conf)
scope = _config('scope', conf)
_lists = _config('lists', conf) or []
_attrs = _config('attrs', conf) or []
_dict_key_attr = _config('dict_key_attr', conf, 'dn')
attrs = _lists + _attrs + [_dict_key_attr]
if not attrs:
attrs = None
# Perform the search
try:
result = __salt__['ldap.search'](_filter, _dn, scope, attrs,
**connargs)['results']
except IndexError: # we got no results for this search
log.debug('LDAP search returned no results for filter %s', _filter)
result = {}
except Exception:
log.critical(
'Failed to retrieve pillar data from LDAP:\n', exc_info=True
)
return {}
return result
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
config_file):
'''
Execute LDAP searches and return the aggregated data
'''
config_template = None
try:
config_template = _render_template(config_file)
except jinja2.exceptions.TemplateNotFound:
log.debug('pillar_ldap: missing configuration file %s', config_file)
except Exception:
log.debug('pillar_ldap: failed to render template for %s',
config_file, exc_info=True)
if not config_template:
# We don't have a config file
return {}
import salt.utils.yaml
try:
opts = salt.utils.yaml.safe_load(config_template) or {}
opts['conf_file'] = config_file
except Exception as err:
import salt.log
msg = 'pillar_ldap: error parsing configuration file: {0} - {1}'.format(
config_file, err
)
if salt.log.is_console_configured():
log.warning(msg)
else:
print(msg)
return {}
else:
if not isinstance(opts, dict):
log.warning(
'pillar_ldap: %s is invalidly formatted, must be a YAML '
'dictionary. See the documentation for more information.',
config_file
)
return {}
if 'search_order' not in opts:
log.warning(
'pillar_ldap: search_order missing from configuration. See the '
'documentation for more information.'
)
return {}
data = {}
for source in opts['search_order']:
config = opts[source]
result = _do_search(config)
log.debug('source %s got result %s', source, result)
if result:
data = _result_to_dict(data, result, config, source)
return data
|
saltstack/salt
|
salt/pillar/pillar_ldap.py
|
_result_to_dict
|
python
|
def _result_to_dict(data, result, conf, source):
'''
Aggregates LDAP search result based on rules, returns a dictionary.
Rules:
Attributes tagged in the pillar config as 'attrs' or 'lists' are
scanned for a 'key=value' format (non matching entries are ignored.
Entries matching the 'attrs' tag overwrite previous values where
the key matches a previous result.
Entries matching the 'lists' tag are appended to list of values where
the key matches a previous result.
All Matching entries are then written directly to the pillar data
dictionary as data[key] = value.
For example, search result:
{ saltKeyValue': ['ntpserver=ntp.acme.local', 'foo=myfoo'],
'saltList': ['vhost=www.acme.net', 'vhost=www.acme.local'] }
is written to the pillar data dictionary as:
{ 'ntpserver': 'ntp.acme.local', 'foo': 'myfoo',
'vhost': ['www.acme.net', 'www.acme.local'] }
'''
attrs = _config('attrs', conf) or []
lists = _config('lists', conf) or []
dict_key_attr = _config('dict_key_attr', conf) or 'dn'
# TODO:
# deprecate the default 'mode: split' and make the more
# straightforward 'mode: map' the new default
mode = _config('mode', conf) or 'split'
if mode == 'map':
data[source] = []
for record in result:
ret = {}
if 'dn' in attrs or 'distinguishedName' in attrs:
log.debug('dn: %s', record[0])
ret['dn'] = record[0]
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
data[source].append(ret)
elif mode == 'dict':
data[source] = {}
for record in result:
ret = {}
distinguished_name = record[0]
log.debug('dn: %s', distinguished_name)
if 'dn' in attrs or 'distinguishedName' in attrs:
ret['dn'] = distinguished_name
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
if dict_key_attr in ['dn', 'distinguishedName']:
dict_key = distinguished_name
else:
dict_key = ','.join(sorted(record.get(dict_key_attr, [])))
try:
data[source][dict_key].append(ret)
except KeyError:
data[source][dict_key] = [ret]
elif mode == 'split':
for key in result[0][1]:
if key in attrs:
for item in result.get(key):
skey, sval = item.split('=', 1)
data[skey] = sval
elif key in lists:
for item in result.get(key):
if '=' in item:
skey, sval = item.split('=', 1)
if skey not in data:
data[skey] = [sval]
else:
data[skey].append(sval)
return data
|
Aggregates LDAP search result based on rules, returns a dictionary.
Rules:
Attributes tagged in the pillar config as 'attrs' or 'lists' are
scanned for a 'key=value' format (non matching entries are ignored.
Entries matching the 'attrs' tag overwrite previous values where
the key matches a previous result.
Entries matching the 'lists' tag are appended to list of values where
the key matches a previous result.
All Matching entries are then written directly to the pillar data
dictionary as data[key] = value.
For example, search result:
{ saltKeyValue': ['ntpserver=ntp.acme.local', 'foo=myfoo'],
'saltList': ['vhost=www.acme.net', 'vhost=www.acme.local'] }
is written to the pillar data dictionary as:
{ 'ntpserver': 'ntp.acme.local', 'foo': 'myfoo',
'vhost': ['www.acme.net', 'www.acme.local'] }
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L179-L267
| null |
# -*- coding: utf-8 -*-
'''
Use LDAP data as a Pillar source
This pillar module executes a series of LDAP searches.
Data returned by these searches are aggregated, whereby data returned by later
searches override data by previous searches with the same key.
The final result is merged with existing pillar data.
The configuration of this external pillar module is done via an external
file which provides the actual configuration for the LDAP searches.
===============================
Configuring the LDAP ext_pillar
===============================
The basic configuration is part of the `master configuration
<master-configuration-ext-pillar>`_.
.. code-block:: yaml
ext_pillar:
- pillar_ldap: /etc/salt/master.d/pillar_ldap.yaml
.. note::
When placing the file in the ``master.d`` directory, make sure its name
doesn't end in ``.conf``, otherwise the salt-master process will attempt
to parse its content.
.. warning::
Make sure this file has very restrictive permissions, as it will contain
possibly sensitive LDAP credentials!
The only required key in the master configuration is ``pillar_ldap`` pointing
to a file containing the actual configuration.
Configuring the LDAP searches
=============================
The file is processed using `Salt's Renderers <renderers>` which makes it
possible to reference grains within the configuration.
.. warning::
When using Jinja in this file, make sure to do it in a way which prevents
leaking sensitive information. A rogue minion could send arbitrary grains
to trick the master into returning secret data.
Use only the 'id' grain which is verified through the minion's key/cert.
Map Mode
--------
The ``it-admins`` configuration below returns the Pillar ``it-admins`` by:
- filtering for:
- members of the group ``it-admins``
- objects with ``objectclass=user``
- returning the data of users, where each user is a dictionary containing the
configured string or list attributes.
Configuration
*************
.. code-block:: yaml
salt-users:
server: ldap.company.tld
port: 389
tls: true
dn: 'dc=company,dc=tld'
binddn: 'cn=salt-pillars,ou=users,dc=company,dc=tld'
bindpw: bi7ieBai5Ano
referrals: false
anonymous: false
mode: map
dn: 'ou=users,dc=company,dc=tld'
filter: '(&(memberof=cn=it-admins,ou=groups,dc=company,dc=tld)(objectclass=user))'
attrs:
- cn
- displayName
- givenName
- sn
lists:
- memberOf
search_order:
- salt-users
Result
******
.. code-block:: python
{
'salt-users': [
{
'cn': 'cn=johndoe,ou=users,dc=company,dc=tld',
'displayName': 'John Doe'
'givenName': 'John'
'sn': 'Doe'
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team01,ou=groups,dc=company'
]
},
{
'cn': 'cn=janedoe,ou=users,dc=company,dc=tld',
'displayName': 'Jane Doe',
'givenName': 'Jane',
'sn': 'Doe',
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team02,ou=groups,dc=company'
]
}
]
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import salt libs
import salt.utils.data
from salt.exceptions import SaltInvocationError
# Import third party libs
import jinja2
try:
import ldap # pylint: disable=W0611
HAS_LDAP = True
except ImportError:
HAS_LDAP = False
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if ldap module is installed
'''
if HAS_LDAP:
return 'pillar_ldap'
else:
return False
def _render_template(config_file):
'''
Render config template, substituting grains where found.
'''
dirname, filename = os.path.split(config_file)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname))
template = env.get_template(filename)
return template.render(__grains__)
def _config(name, conf, default=None):
'''
Return a value for 'name' from the config file options. If the 'name' is
not in the config, the 'default' value is returned. This method converts
unicode values to str type under python 2.
'''
try:
value = conf[name]
except KeyError:
value = default
return salt.utils.data.decode(value, to_str=True)
def _do_search(conf):
'''
Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use.
'''
# Build LDAP connection args
connargs = {}
for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']:
connargs[name] = _config(name, conf)
if connargs['binddn'] and connargs['bindpw']:
connargs['anonymous'] = False
# Build search args
try:
_filter = conf['filter']
except KeyError:
raise SaltInvocationError('missing filter')
_dn = _config('dn', conf)
scope = _config('scope', conf)
_lists = _config('lists', conf) or []
_attrs = _config('attrs', conf) or []
_dict_key_attr = _config('dict_key_attr', conf, 'dn')
attrs = _lists + _attrs + [_dict_key_attr]
if not attrs:
attrs = None
# Perform the search
try:
result = __salt__['ldap.search'](_filter, _dn, scope, attrs,
**connargs)['results']
except IndexError: # we got no results for this search
log.debug('LDAP search returned no results for filter %s', _filter)
result = {}
except Exception:
log.critical(
'Failed to retrieve pillar data from LDAP:\n', exc_info=True
)
return {}
return result
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
config_file):
'''
Execute LDAP searches and return the aggregated data
'''
config_template = None
try:
config_template = _render_template(config_file)
except jinja2.exceptions.TemplateNotFound:
log.debug('pillar_ldap: missing configuration file %s', config_file)
except Exception:
log.debug('pillar_ldap: failed to render template for %s',
config_file, exc_info=True)
if not config_template:
# We don't have a config file
return {}
import salt.utils.yaml
try:
opts = salt.utils.yaml.safe_load(config_template) or {}
opts['conf_file'] = config_file
except Exception as err:
import salt.log
msg = 'pillar_ldap: error parsing configuration file: {0} - {1}'.format(
config_file, err
)
if salt.log.is_console_configured():
log.warning(msg)
else:
print(msg)
return {}
else:
if not isinstance(opts, dict):
log.warning(
'pillar_ldap: %s is invalidly formatted, must be a YAML '
'dictionary. See the documentation for more information.',
config_file
)
return {}
if 'search_order' not in opts:
log.warning(
'pillar_ldap: search_order missing from configuration. See the '
'documentation for more information.'
)
return {}
data = {}
for source in opts['search_order']:
config = opts[source]
result = _do_search(config)
log.debug('source %s got result %s', source, result)
if result:
data = _result_to_dict(data, result, config, source)
return data
|
saltstack/salt
|
salt/pillar/pillar_ldap.py
|
_do_search
|
python
|
def _do_search(conf):
'''
Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use.
'''
# Build LDAP connection args
connargs = {}
for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']:
connargs[name] = _config(name, conf)
if connargs['binddn'] and connargs['bindpw']:
connargs['anonymous'] = False
# Build search args
try:
_filter = conf['filter']
except KeyError:
raise SaltInvocationError('missing filter')
_dn = _config('dn', conf)
scope = _config('scope', conf)
_lists = _config('lists', conf) or []
_attrs = _config('attrs', conf) or []
_dict_key_attr = _config('dict_key_attr', conf, 'dn')
attrs = _lists + _attrs + [_dict_key_attr]
if not attrs:
attrs = None
# Perform the search
try:
result = __salt__['ldap.search'](_filter, _dn, scope, attrs,
**connargs)['results']
except IndexError: # we got no results for this search
log.debug('LDAP search returned no results for filter %s', _filter)
result = {}
except Exception:
log.critical(
'Failed to retrieve pillar data from LDAP:\n', exc_info=True
)
return {}
return result
|
Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L270-L306
| null |
# -*- coding: utf-8 -*-
'''
Use LDAP data as a Pillar source
This pillar module executes a series of LDAP searches.
Data returned by these searches are aggregated, whereby data returned by later
searches override data by previous searches with the same key.
The final result is merged with existing pillar data.
The configuration of this external pillar module is done via an external
file which provides the actual configuration for the LDAP searches.
===============================
Configuring the LDAP ext_pillar
===============================
The basic configuration is part of the `master configuration
<master-configuration-ext-pillar>`_.
.. code-block:: yaml
ext_pillar:
- pillar_ldap: /etc/salt/master.d/pillar_ldap.yaml
.. note::
When placing the file in the ``master.d`` directory, make sure its name
doesn't end in ``.conf``, otherwise the salt-master process will attempt
to parse its content.
.. warning::
Make sure this file has very restrictive permissions, as it will contain
possibly sensitive LDAP credentials!
The only required key in the master configuration is ``pillar_ldap`` pointing
to a file containing the actual configuration.
Configuring the LDAP searches
=============================
The file is processed using `Salt's Renderers <renderers>` which makes it
possible to reference grains within the configuration.
.. warning::
When using Jinja in this file, make sure to do it in a way which prevents
leaking sensitive information. A rogue minion could send arbitrary grains
to trick the master into returning secret data.
Use only the 'id' grain which is verified through the minion's key/cert.
Map Mode
--------
The ``it-admins`` configuration below returns the Pillar ``it-admins`` by:
- filtering for:
- members of the group ``it-admins``
- objects with ``objectclass=user``
- returning the data of users, where each user is a dictionary containing the
configured string or list attributes.
Configuration
*************
.. code-block:: yaml
salt-users:
server: ldap.company.tld
port: 389
tls: true
dn: 'dc=company,dc=tld'
binddn: 'cn=salt-pillars,ou=users,dc=company,dc=tld'
bindpw: bi7ieBai5Ano
referrals: false
anonymous: false
mode: map
dn: 'ou=users,dc=company,dc=tld'
filter: '(&(memberof=cn=it-admins,ou=groups,dc=company,dc=tld)(objectclass=user))'
attrs:
- cn
- displayName
- givenName
- sn
lists:
- memberOf
search_order:
- salt-users
Result
******
.. code-block:: python
{
'salt-users': [
{
'cn': 'cn=johndoe,ou=users,dc=company,dc=tld',
'displayName': 'John Doe'
'givenName': 'John'
'sn': 'Doe'
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team01,ou=groups,dc=company'
]
},
{
'cn': 'cn=janedoe,ou=users,dc=company,dc=tld',
'displayName': 'Jane Doe',
'givenName': 'Jane',
'sn': 'Doe',
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team02,ou=groups,dc=company'
]
}
]
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import salt libs
import salt.utils.data
from salt.exceptions import SaltInvocationError
# Import third party libs
import jinja2
try:
import ldap # pylint: disable=W0611
HAS_LDAP = True
except ImportError:
HAS_LDAP = False
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if ldap module is installed
'''
if HAS_LDAP:
return 'pillar_ldap'
else:
return False
def _render_template(config_file):
'''
Render config template, substituting grains where found.
'''
dirname, filename = os.path.split(config_file)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname))
template = env.get_template(filename)
return template.render(__grains__)
def _config(name, conf, default=None):
'''
Return a value for 'name' from the config file options. If the 'name' is
not in the config, the 'default' value is returned. This method converts
unicode values to str type under python 2.
'''
try:
value = conf[name]
except KeyError:
value = default
return salt.utils.data.decode(value, to_str=True)
def _result_to_dict(data, result, conf, source):
'''
Aggregates LDAP search result based on rules, returns a dictionary.
Rules:
Attributes tagged in the pillar config as 'attrs' or 'lists' are
scanned for a 'key=value' format (non matching entries are ignored.
Entries matching the 'attrs' tag overwrite previous values where
the key matches a previous result.
Entries matching the 'lists' tag are appended to list of values where
the key matches a previous result.
All Matching entries are then written directly to the pillar data
dictionary as data[key] = value.
For example, search result:
{ saltKeyValue': ['ntpserver=ntp.acme.local', 'foo=myfoo'],
'saltList': ['vhost=www.acme.net', 'vhost=www.acme.local'] }
is written to the pillar data dictionary as:
{ 'ntpserver': 'ntp.acme.local', 'foo': 'myfoo',
'vhost': ['www.acme.net', 'www.acme.local'] }
'''
attrs = _config('attrs', conf) or []
lists = _config('lists', conf) or []
dict_key_attr = _config('dict_key_attr', conf) or 'dn'
# TODO:
# deprecate the default 'mode: split' and make the more
# straightforward 'mode: map' the new default
mode = _config('mode', conf) or 'split'
if mode == 'map':
data[source] = []
for record in result:
ret = {}
if 'dn' in attrs or 'distinguishedName' in attrs:
log.debug('dn: %s', record[0])
ret['dn'] = record[0]
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
data[source].append(ret)
elif mode == 'dict':
data[source] = {}
for record in result:
ret = {}
distinguished_name = record[0]
log.debug('dn: %s', distinguished_name)
if 'dn' in attrs or 'distinguishedName' in attrs:
ret['dn'] = distinguished_name
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
if dict_key_attr in ['dn', 'distinguishedName']:
dict_key = distinguished_name
else:
dict_key = ','.join(sorted(record.get(dict_key_attr, [])))
try:
data[source][dict_key].append(ret)
except KeyError:
data[source][dict_key] = [ret]
elif mode == 'split':
for key in result[0][1]:
if key in attrs:
for item in result.get(key):
skey, sval = item.split('=', 1)
data[skey] = sval
elif key in lists:
for item in result.get(key):
if '=' in item:
skey, sval = item.split('=', 1)
if skey not in data:
data[skey] = [sval]
else:
data[skey].append(sval)
return data
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
config_file):
'''
Execute LDAP searches and return the aggregated data
'''
config_template = None
try:
config_template = _render_template(config_file)
except jinja2.exceptions.TemplateNotFound:
log.debug('pillar_ldap: missing configuration file %s', config_file)
except Exception:
log.debug('pillar_ldap: failed to render template for %s',
config_file, exc_info=True)
if not config_template:
# We don't have a config file
return {}
import salt.utils.yaml
try:
opts = salt.utils.yaml.safe_load(config_template) or {}
opts['conf_file'] = config_file
except Exception as err:
import salt.log
msg = 'pillar_ldap: error parsing configuration file: {0} - {1}'.format(
config_file, err
)
if salt.log.is_console_configured():
log.warning(msg)
else:
print(msg)
return {}
else:
if not isinstance(opts, dict):
log.warning(
'pillar_ldap: %s is invalidly formatted, must be a YAML '
'dictionary. See the documentation for more information.',
config_file
)
return {}
if 'search_order' not in opts:
log.warning(
'pillar_ldap: search_order missing from configuration. See the '
'documentation for more information.'
)
return {}
data = {}
for source in opts['search_order']:
config = opts[source]
result = _do_search(config)
log.debug('source %s got result %s', source, result)
if result:
data = _result_to_dict(data, result, config, source)
return data
|
saltstack/salt
|
salt/pillar/pillar_ldap.py
|
ext_pillar
|
python
|
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
config_file):
'''
Execute LDAP searches and return the aggregated data
'''
config_template = None
try:
config_template = _render_template(config_file)
except jinja2.exceptions.TemplateNotFound:
log.debug('pillar_ldap: missing configuration file %s', config_file)
except Exception:
log.debug('pillar_ldap: failed to render template for %s',
config_file, exc_info=True)
if not config_template:
# We don't have a config file
return {}
import salt.utils.yaml
try:
opts = salt.utils.yaml.safe_load(config_template) or {}
opts['conf_file'] = config_file
except Exception as err:
import salt.log
msg = 'pillar_ldap: error parsing configuration file: {0} - {1}'.format(
config_file, err
)
if salt.log.is_console_configured():
log.warning(msg)
else:
print(msg)
return {}
else:
if not isinstance(opts, dict):
log.warning(
'pillar_ldap: %s is invalidly formatted, must be a YAML '
'dictionary. See the documentation for more information.',
config_file
)
return {}
if 'search_order' not in opts:
log.warning(
'pillar_ldap: search_order missing from configuration. See the '
'documentation for more information.'
)
return {}
data = {}
for source in opts['search_order']:
config = opts[source]
result = _do_search(config)
log.debug('source %s got result %s', source, result)
if result:
data = _result_to_dict(data, result, config, source)
return data
|
Execute LDAP searches and return the aggregated data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/pillar_ldap.py#L309-L365
|
[
"def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n",
"def is_console_configured():\n return __CONSOLE_CONFIGURED\n",
"def _render_template(config_file):\n '''\n Render config template, substituting grains where found.\n '''\n dirname, filename = os.path.split(config_file)\n env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname))\n template = env.get_template(filename)\n return template.render(__grains__)\n"
] |
# -*- coding: utf-8 -*-
'''
Use LDAP data as a Pillar source
This pillar module executes a series of LDAP searches.
Data returned by these searches are aggregated, whereby data returned by later
searches override data by previous searches with the same key.
The final result is merged with existing pillar data.
The configuration of this external pillar module is done via an external
file which provides the actual configuration for the LDAP searches.
===============================
Configuring the LDAP ext_pillar
===============================
The basic configuration is part of the `master configuration
<master-configuration-ext-pillar>`_.
.. code-block:: yaml
ext_pillar:
- pillar_ldap: /etc/salt/master.d/pillar_ldap.yaml
.. note::
When placing the file in the ``master.d`` directory, make sure its name
doesn't end in ``.conf``, otherwise the salt-master process will attempt
to parse its content.
.. warning::
Make sure this file has very restrictive permissions, as it will contain
possibly sensitive LDAP credentials!
The only required key in the master configuration is ``pillar_ldap`` pointing
to a file containing the actual configuration.
Configuring the LDAP searches
=============================
The file is processed using `Salt's Renderers <renderers>` which makes it
possible to reference grains within the configuration.
.. warning::
When using Jinja in this file, make sure to do it in a way which prevents
leaking sensitive information. A rogue minion could send arbitrary grains
to trick the master into returning secret data.
Use only the 'id' grain which is verified through the minion's key/cert.
Map Mode
--------
The ``it-admins`` configuration below returns the Pillar ``it-admins`` by:
- filtering for:
- members of the group ``it-admins``
- objects with ``objectclass=user``
- returning the data of users, where each user is a dictionary containing the
configured string or list attributes.
Configuration
*************
.. code-block:: yaml
salt-users:
server: ldap.company.tld
port: 389
tls: true
dn: 'dc=company,dc=tld'
binddn: 'cn=salt-pillars,ou=users,dc=company,dc=tld'
bindpw: bi7ieBai5Ano
referrals: false
anonymous: false
mode: map
dn: 'ou=users,dc=company,dc=tld'
filter: '(&(memberof=cn=it-admins,ou=groups,dc=company,dc=tld)(objectclass=user))'
attrs:
- cn
- displayName
- givenName
- sn
lists:
- memberOf
search_order:
- salt-users
Result
******
.. code-block:: python
{
'salt-users': [
{
'cn': 'cn=johndoe,ou=users,dc=company,dc=tld',
'displayName': 'John Doe'
'givenName': 'John'
'sn': 'Doe'
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team01,ou=groups,dc=company'
]
},
{
'cn': 'cn=janedoe,ou=users,dc=company,dc=tld',
'displayName': 'Jane Doe',
'givenName': 'Jane',
'sn': 'Doe',
'memberOf': [
'cn=it-admins,ou=groups,dc=company,dc=tld',
'cn=team02,ou=groups,dc=company'
]
}
]
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import salt libs
import salt.utils.data
from salt.exceptions import SaltInvocationError
# Import third party libs
import jinja2
try:
import ldap # pylint: disable=W0611
HAS_LDAP = True
except ImportError:
HAS_LDAP = False
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if ldap module is installed
'''
if HAS_LDAP:
return 'pillar_ldap'
else:
return False
def _render_template(config_file):
'''
Render config template, substituting grains where found.
'''
dirname, filename = os.path.split(config_file)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname))
template = env.get_template(filename)
return template.render(__grains__)
def _config(name, conf, default=None):
'''
Return a value for 'name' from the config file options. If the 'name' is
not in the config, the 'default' value is returned. This method converts
unicode values to str type under python 2.
'''
try:
value = conf[name]
except KeyError:
value = default
return salt.utils.data.decode(value, to_str=True)
def _result_to_dict(data, result, conf, source):
'''
Aggregates LDAP search result based on rules, returns a dictionary.
Rules:
Attributes tagged in the pillar config as 'attrs' or 'lists' are
scanned for a 'key=value' format (non matching entries are ignored.
Entries matching the 'attrs' tag overwrite previous values where
the key matches a previous result.
Entries matching the 'lists' tag are appended to list of values where
the key matches a previous result.
All Matching entries are then written directly to the pillar data
dictionary as data[key] = value.
For example, search result:
{ saltKeyValue': ['ntpserver=ntp.acme.local', 'foo=myfoo'],
'saltList': ['vhost=www.acme.net', 'vhost=www.acme.local'] }
is written to the pillar data dictionary as:
{ 'ntpserver': 'ntp.acme.local', 'foo': 'myfoo',
'vhost': ['www.acme.net', 'www.acme.local'] }
'''
attrs = _config('attrs', conf) or []
lists = _config('lists', conf) or []
dict_key_attr = _config('dict_key_attr', conf) or 'dn'
# TODO:
# deprecate the default 'mode: split' and make the more
# straightforward 'mode: map' the new default
mode = _config('mode', conf) or 'split'
if mode == 'map':
data[source] = []
for record in result:
ret = {}
if 'dn' in attrs or 'distinguishedName' in attrs:
log.debug('dn: %s', record[0])
ret['dn'] = record[0]
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
data[source].append(ret)
elif mode == 'dict':
data[source] = {}
for record in result:
ret = {}
distinguished_name = record[0]
log.debug('dn: %s', distinguished_name)
if 'dn' in attrs or 'distinguishedName' in attrs:
ret['dn'] = distinguished_name
record = record[1]
log.debug('record: %s', record)
for key in record:
if key in attrs:
for item in record.get(key):
ret[key] = item
if key in lists:
ret[key] = record.get(key)
if dict_key_attr in ['dn', 'distinguishedName']:
dict_key = distinguished_name
else:
dict_key = ','.join(sorted(record.get(dict_key_attr, [])))
try:
data[source][dict_key].append(ret)
except KeyError:
data[source][dict_key] = [ret]
elif mode == 'split':
for key in result[0][1]:
if key in attrs:
for item in result.get(key):
skey, sval = item.split('=', 1)
data[skey] = sval
elif key in lists:
for item in result.get(key):
if '=' in item:
skey, sval = item.split('=', 1)
if skey not in data:
data[skey] = [sval]
else:
data[skey].append(sval)
return data
def _do_search(conf):
'''
Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use.
'''
# Build LDAP connection args
connargs = {}
for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']:
connargs[name] = _config(name, conf)
if connargs['binddn'] and connargs['bindpw']:
connargs['anonymous'] = False
# Build search args
try:
_filter = conf['filter']
except KeyError:
raise SaltInvocationError('missing filter')
_dn = _config('dn', conf)
scope = _config('scope', conf)
_lists = _config('lists', conf) or []
_attrs = _config('attrs', conf) or []
_dict_key_attr = _config('dict_key_attr', conf, 'dn')
attrs = _lists + _attrs + [_dict_key_attr]
if not attrs:
attrs = None
# Perform the search
try:
result = __salt__['ldap.search'](_filter, _dn, scope, attrs,
**connargs)['results']
except IndexError: # we got no results for this search
log.debug('LDAP search returned no results for filter %s', _filter)
result = {}
except Exception:
log.critical(
'Failed to retrieve pillar data from LDAP:\n', exc_info=True
)
return {}
return result
|
saltstack/salt
|
salt/states/win_pki.py
|
import_cert
|
python
|
def import_cert(name, cert_format=_DEFAULT_FORMAT, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE,
exportable=True, password='', saltenv='base'):
'''
Import the certificate file into the given certificate store.
:param str name: The path of the certificate file to import.
:param str cert_format: The certificate format. Specify 'cer' for X.509, or 'pfx' for PKCS #12.
:param str context: The name of the certificate store location context.
:param str store: The name of the certificate store.
:param bool exportable: Mark the certificate as exportable. Only applicable to pfx format.
:param str password: The password of the certificate. Only applicable to pfx format.
:param str saltenv: The environment the file resides in.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-imported:
win_pki.import_cert:
- name: salt://win/webserver/certs/site0.cer
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-imported:
win_pki.import_cert:
- name: salt://win/webserver/certs/site0.pfx
- cert_format: pfx
- context: LocalMachine
- store: My
- exportable: True
- password: TestPassword
- saltenv: base
'''
ret = {'name': name,
'changes': dict(),
'comment': six.text_type(),
'result': None}
store_path = r'Cert:\{0}\{1}'.format(context, store)
cached_source_path = __salt__['cp.cache_file'](name, saltenv)
current_certs = __salt__['win_pki.get_certs'](context=context, store=store)
if password:
cert_props = __salt__['win_pki.get_cert_file'](name=cached_source_path, cert_format=cert_format, password=password)
else:
cert_props = __salt__['win_pki.get_cert_file'](name=cached_source_path, cert_format=cert_format)
if cert_props['thumbprint'] in current_certs:
ret['comment'] = ("Certificate '{0}' already contained in store:"
' {1}').format(cert_props['thumbprint'], store_path)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = ("Certificate '{0}' will be imported into store:"
' {1}').format(cert_props['thumbprint'], store_path)
ret['changes'] = {'old': None,
'new': cert_props['thumbprint']}
else:
ret['changes'] = {'old': None,
'new': cert_props['thumbprint']}
ret['result'] = __salt__['win_pki.import_cert'](name=name, cert_format=cert_format,
context=context, store=store,
exportable=exportable, password=password,
saltenv=saltenv)
if ret['result']:
ret['comment'] = ("Certificate '{0}' imported into store:"
' {1}').format(cert_props['thumbprint'], store_path)
else:
ret['comment'] = ("Certificate '{0}' unable to be imported into store:"
' {1}').format(cert_props['thumbprint'], store_path)
return ret
|
Import the certificate file into the given certificate store.
:param str name: The path of the certificate file to import.
:param str cert_format: The certificate format. Specify 'cer' for X.509, or 'pfx' for PKCS #12.
:param str context: The name of the certificate store location context.
:param str store: The name of the certificate store.
:param bool exportable: Mark the certificate as exportable. Only applicable to pfx format.
:param str password: The password of the certificate. Only applicable to pfx format.
:param str saltenv: The environment the file resides in.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-imported:
win_pki.import_cert:
- name: salt://win/webserver/certs/site0.cer
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-imported:
win_pki.import_cert:
- name: salt://win/webserver/certs/site0.pfx
- cert_format: pfx
- context: LocalMachine
- store: My
- exportable: True
- password: TestPassword
- saltenv: base
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_pki.py#L30-L101
| null |
# -*- coding: utf-8 -*-
'''
Microsoft certificate management via the Pki PowerShell module.
:platform: Windows
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
_DEFAULT_CONTEXT = 'LocalMachine'
_DEFAULT_FORMAT = 'cer'
_DEFAULT_STORE = 'My'
# import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Load only on minions that have the win_pki module.
'''
if 'win_pki.get_stores' in __salt__:
return True
return False
def remove_cert(name, thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE):
'''
Remove the certificate from the given certificate store.
:param str thumbprint: The thumbprint value of the target certificate.
:param str context: The name of the certificate store location context.
:param str store: The name of the certificate store.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-removed:
win_pki.remove_cert:
- thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-removed:
win_pki.remove_cert:
- thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF
- context: LocalMachine
- store: My
'''
ret = {'name': name,
'changes': dict(),
'comment': six.text_type(),
'result': None}
store_path = r'Cert:\{0}\{1}'.format(context, store)
current_certs = __salt__['win_pki.get_certs'](context=context, store=store)
if thumbprint not in current_certs:
ret['comment'] = "Certificate '{0}' already removed from store: {1}".format(thumbprint,
store_path)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = "Certificate '{0}' will be removed from store: {1}".format(thumbprint,
store_path)
ret['changes'] = {'old': thumbprint,
'new': None}
else:
ret['changes'] = {'old': thumbprint,
'new': None}
ret['result'] = __salt__['win_pki.remove_cert'](thumbprint=thumbprint, context=context,
store=store)
if ret['result']:
ret['comment'] = "Certificate '{0}' removed from store: {1}".format(thumbprint, store_path)
else:
ret['comment'] = "Certificate '{0}' unable to be removed from store: {1}".format(thumbprint,
store_path)
return ret
|
saltstack/salt
|
salt/states/win_pki.py
|
remove_cert
|
python
|
def remove_cert(name, thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE):
'''
Remove the certificate from the given certificate store.
:param str thumbprint: The thumbprint value of the target certificate.
:param str context: The name of the certificate store location context.
:param str store: The name of the certificate store.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-removed:
win_pki.remove_cert:
- thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-removed:
win_pki.remove_cert:
- thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF
- context: LocalMachine
- store: My
'''
ret = {'name': name,
'changes': dict(),
'comment': six.text_type(),
'result': None}
store_path = r'Cert:\{0}\{1}'.format(context, store)
current_certs = __salt__['win_pki.get_certs'](context=context, store=store)
if thumbprint not in current_certs:
ret['comment'] = "Certificate '{0}' already removed from store: {1}".format(thumbprint,
store_path)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = "Certificate '{0}' will be removed from store: {1}".format(thumbprint,
store_path)
ret['changes'] = {'old': thumbprint,
'new': None}
else:
ret['changes'] = {'old': thumbprint,
'new': None}
ret['result'] = __salt__['win_pki.remove_cert'](thumbprint=thumbprint, context=context,
store=store)
if ret['result']:
ret['comment'] = "Certificate '{0}' removed from store: {1}".format(thumbprint, store_path)
else:
ret['comment'] = "Certificate '{0}' unable to be removed from store: {1}".format(thumbprint,
store_path)
return ret
|
Remove the certificate from the given certificate store.
:param str thumbprint: The thumbprint value of the target certificate.
:param str context: The name of the certificate store location context.
:param str store: The name of the certificate store.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-removed:
win_pki.remove_cert:
- thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-removed:
win_pki.remove_cert:
- thumbprint: 9988776655443322111000AAABBBCCCDDDEEEFFF
- context: LocalMachine
- store: My
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_pki.py#L104-L157
| null |
# -*- coding: utf-8 -*-
'''
Microsoft certificate management via the Pki PowerShell module.
:platform: Windows
.. versionadded:: 2016.11.0
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
_DEFAULT_CONTEXT = 'LocalMachine'
_DEFAULT_FORMAT = 'cer'
_DEFAULT_STORE = 'My'
# import 3rd party libs
from salt.ext import six
def __virtual__():
'''
Load only on minions that have the win_pki module.
'''
if 'win_pki.get_stores' in __salt__:
return True
return False
def import_cert(name, cert_format=_DEFAULT_FORMAT, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE,
exportable=True, password='', saltenv='base'):
'''
Import the certificate file into the given certificate store.
:param str name: The path of the certificate file to import.
:param str cert_format: The certificate format. Specify 'cer' for X.509, or 'pfx' for PKCS #12.
:param str context: The name of the certificate store location context.
:param str store: The name of the certificate store.
:param bool exportable: Mark the certificate as exportable. Only applicable to pfx format.
:param str password: The password of the certificate. Only applicable to pfx format.
:param str saltenv: The environment the file resides in.
Example of usage with only the required arguments:
.. code-block:: yaml
site0-cert-imported:
win_pki.import_cert:
- name: salt://win/webserver/certs/site0.cer
Example of usage specifying all available arguments:
.. code-block:: yaml
site0-cert-imported:
win_pki.import_cert:
- name: salt://win/webserver/certs/site0.pfx
- cert_format: pfx
- context: LocalMachine
- store: My
- exportable: True
- password: TestPassword
- saltenv: base
'''
ret = {'name': name,
'changes': dict(),
'comment': six.text_type(),
'result': None}
store_path = r'Cert:\{0}\{1}'.format(context, store)
cached_source_path = __salt__['cp.cache_file'](name, saltenv)
current_certs = __salt__['win_pki.get_certs'](context=context, store=store)
if password:
cert_props = __salt__['win_pki.get_cert_file'](name=cached_source_path, cert_format=cert_format, password=password)
else:
cert_props = __salt__['win_pki.get_cert_file'](name=cached_source_path, cert_format=cert_format)
if cert_props['thumbprint'] in current_certs:
ret['comment'] = ("Certificate '{0}' already contained in store:"
' {1}').format(cert_props['thumbprint'], store_path)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = ("Certificate '{0}' will be imported into store:"
' {1}').format(cert_props['thumbprint'], store_path)
ret['changes'] = {'old': None,
'new': cert_props['thumbprint']}
else:
ret['changes'] = {'old': None,
'new': cert_props['thumbprint']}
ret['result'] = __salt__['win_pki.import_cert'](name=name, cert_format=cert_format,
context=context, store=store,
exportable=exportable, password=password,
saltenv=saltenv)
if ret['result']:
ret['comment'] = ("Certificate '{0}' imported into store:"
' {1}').format(cert_props['thumbprint'], store_path)
else:
ret['comment'] = ("Certificate '{0}' unable to be imported into store:"
' {1}').format(cert_props['thumbprint'], store_path)
return ret
|
saltstack/salt
|
salt/sdb/etcd_db.py
|
set_
|
python
|
def set_(key, value, service=None, profile=None): # pylint: disable=W0613
'''
Set a key/value pair in the etcd service
'''
client = _get_conn(profile)
client.set(key, value)
return get(key, service, profile)
|
Set a key/value pair in the etcd service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/etcd_db.py#L63-L69
|
[
"def get(key, service=None, profile=None): # pylint: disable=W0613\n '''\n Get a value from the etcd service\n '''\n client = _get_conn(profile)\n result = client.get(key)\n return result.value\n",
"def _get_conn(profile):\n '''\n Get a connection\n '''\n return salt.utils.etcd_util.get_conn(profile)\n"
] |
# -*- coding: utf-8 -*-
'''
etcd Database Module
:maintainer: SaltStack
:maturity: New
:depends: python-etcd
:platform: all
.. versionadded:: 2015.5.0
This module allows access to the etcd database using an ``sdb://`` URI. This
package is located at ``https://pypi.python.org/pypi/python-etcd``.
Like all sdb modules, the etcd module requires a configuration profile to
be configured in either the minion or master configuration file. This profile
requires very little. In the example:
.. code-block:: yaml
myetcd:
driver: etcd
etcd.host: 127.0.0.1
etcd.port: 2379
The ``driver`` refers to the etcd module, ``etcd.host`` refers to the host that
is hosting the etcd database and ``etcd.port`` refers to the port on that host.
.. code-block:: yaml
password: sdb://myetcd/mypassword
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
try:
import salt.utils.etcd_util
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
log = logging.getLogger(__name__)
__func_alias__ = {
'set_': 'set'
}
__virtualname__ = 'etcd'
def __virtual__():
'''
Only load the module if keyring is installed
'''
if HAS_LIBS:
return __virtualname__
return False
def get(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a value from the etcd service
'''
client = _get_conn(profile)
result = client.get(key)
return result.value
def delete(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a value from the etcd service
'''
client = _get_conn(profile)
try:
client.delete(key)
return True
except Exception:
return False
def _get_conn(profile):
'''
Get a connection
'''
return salt.utils.etcd_util.get_conn(profile)
|
saltstack/salt
|
salt/sdb/etcd_db.py
|
get
|
python
|
def get(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a value from the etcd service
'''
client = _get_conn(profile)
result = client.get(key)
return result.value
|
Get a value from the etcd service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/etcd_db.py#L72-L78
|
[
"def _get_conn(profile):\n '''\n Get a connection\n '''\n return salt.utils.etcd_util.get_conn(profile)\n"
] |
# -*- coding: utf-8 -*-
'''
etcd Database Module
:maintainer: SaltStack
:maturity: New
:depends: python-etcd
:platform: all
.. versionadded:: 2015.5.0
This module allows access to the etcd database using an ``sdb://`` URI. This
package is located at ``https://pypi.python.org/pypi/python-etcd``.
Like all sdb modules, the etcd module requires a configuration profile to
be configured in either the minion or master configuration file. This profile
requires very little. In the example:
.. code-block:: yaml
myetcd:
driver: etcd
etcd.host: 127.0.0.1
etcd.port: 2379
The ``driver`` refers to the etcd module, ``etcd.host`` refers to the host that
is hosting the etcd database and ``etcd.port`` refers to the port on that host.
.. code-block:: yaml
password: sdb://myetcd/mypassword
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
try:
import salt.utils.etcd_util
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
log = logging.getLogger(__name__)
__func_alias__ = {
'set_': 'set'
}
__virtualname__ = 'etcd'
def __virtual__():
'''
Only load the module if keyring is installed
'''
if HAS_LIBS:
return __virtualname__
return False
def set_(key, value, service=None, profile=None): # pylint: disable=W0613
'''
Set a key/value pair in the etcd service
'''
client = _get_conn(profile)
client.set(key, value)
return get(key, service, profile)
def delete(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a value from the etcd service
'''
client = _get_conn(profile)
try:
client.delete(key)
return True
except Exception:
return False
def _get_conn(profile):
'''
Get a connection
'''
return salt.utils.etcd_util.get_conn(profile)
|
saltstack/salt
|
salt/sdb/etcd_db.py
|
delete
|
python
|
def delete(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a value from the etcd service
'''
client = _get_conn(profile)
try:
client.delete(key)
return True
except Exception:
return False
|
Get a value from the etcd service
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/etcd_db.py#L81-L90
|
[
"def _get_conn(profile):\n '''\n Get a connection\n '''\n return salt.utils.etcd_util.get_conn(profile)\n"
] |
# -*- coding: utf-8 -*-
'''
etcd Database Module
:maintainer: SaltStack
:maturity: New
:depends: python-etcd
:platform: all
.. versionadded:: 2015.5.0
This module allows access to the etcd database using an ``sdb://`` URI. This
package is located at ``https://pypi.python.org/pypi/python-etcd``.
Like all sdb modules, the etcd module requires a configuration profile to
be configured in either the minion or master configuration file. This profile
requires very little. In the example:
.. code-block:: yaml
myetcd:
driver: etcd
etcd.host: 127.0.0.1
etcd.port: 2379
The ``driver`` refers to the etcd module, ``etcd.host`` refers to the host that
is hosting the etcd database and ``etcd.port`` refers to the port on that host.
.. code-block:: yaml
password: sdb://myetcd/mypassword
'''
# import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
try:
import salt.utils.etcd_util
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
log = logging.getLogger(__name__)
__func_alias__ = {
'set_': 'set'
}
__virtualname__ = 'etcd'
def __virtual__():
'''
Only load the module if keyring is installed
'''
if HAS_LIBS:
return __virtualname__
return False
def set_(key, value, service=None, profile=None): # pylint: disable=W0613
'''
Set a key/value pair in the etcd service
'''
client = _get_conn(profile)
client.set(key, value)
return get(key, service, profile)
def get(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a value from the etcd service
'''
client = _get_conn(profile)
result = client.get(key)
return result.value
def _get_conn(profile):
'''
Get a connection
'''
return salt.utils.etcd_util.get_conn(profile)
|
saltstack/salt
|
salt/states/nftables.py
|
chain_present
|
python
|
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['nftables.check_chain'](table, name, family=family)
if chain_check['result'] is True:
ret['result'] = True
ret['comment'] = ('nftables {0} chain is already exist in {1} table for {2}'
.format(name, table, family))
return ret
res = __salt__['nftables.new_chain'](
table,
name,
table_type=table_type,
hook=hook,
priority=priority,
family=family
)
if res['result'] is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('nftables {0} chain in {1} table create success for {2}'
.format(name, table, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
name,
table,
res['comment'].strip(),
family
)
return ret
|
.. versionadded:: 2014.7.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nftables.py#L129-L180
| null |
# -*- coding: utf-8 -*-
'''
Management of nftables
======================
This is an nftables-specific module designed to manage Linux firewalls. It is
expected that this state module, and other system-specific firewall states, may
at some point be deprecated in favor of a more generic `firewall` state.
.. code-block:: yaml
httpd:
nftables.append:
- table: filter
- chain: input
- jump: accept
- match: state
- connstate: new
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.append:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.insert:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.insert:
- position: 1
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
output:
nftables.chain_present:
- family: ip
- table: filter
output:
nftables.chain_absent:
- family: ip
- table: filter
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if the locale module is available in __salt__
'''
return 'nftables' if 'nftables.version' in __salt__ else False
def chain_absent(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.7.0
Verify the chain is absent.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['nftables.check_chain'](table, name, family)
if not chain_check:
ret['result'] = True
ret['comment'] = ('nftables {0} chain is already absent in {1} table for {2}'
.format(name, table, family))
return ret
flush_chain = __salt__['nftables.flush'](table, name, family)
if flush_chain:
command = __salt__['nftables.delete_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('nftables {0} chain in {1} table delete success for {2}'
.format(name, table, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
.format(name, table, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
name,
table,
flush_chain.strip(),
family
)
return ret
def append(name, family='ipv4', **kwargs):
'''
.. versionadded:: 0.17.0
Append a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True, family=family, command='add', **kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
res = __salt__['nftables.append'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Set and Saved nftables rule for {0} to: '
'{1} for {2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set nftables rule for {0}.\n'
'Attempted rule was {1} for {2}.\n'
'{3}').format(
name,
command.strip(), family, res['comment'])
return ret
def insert(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True,
family=family,
command='insert',
**kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
res = __salt__['nftables.insert'](kwargs['table'],
kwargs['chain'],
kwargs['position'],
rule,
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Set and Saved nftables rule for {0} to: '
'{1} for {2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set nftables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def delete(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True, family=family, command='D', **kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if not res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already absent for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be deleted for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'position' in kwargs:
res = __salt__['nftables.delete'](
kwargs['table'],
kwargs['chain'],
family=family,
position=kwargs['position'])
else:
res = __salt__['nftables.delete'](
kwargs['table'],
kwargs['chain'],
family=family,
rule=rule)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Delete nftables rule for {0} {1}'.format(
name,
command.strip())
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Deleted and Saved nftables rule for {0} for {1}'
'{2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to delete nftables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def flush(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Flush current nftables state
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if 'table' not in kwargs:
kwargs['table'] = 'filter'
res = __salt__['nftables.check_table'](kwargs['table'], family=family)
if not res['result']:
ret['result'] = False
ret['comment'] = 'Failed to flush table {0} in family {1}, table does not exist.'.format(
kwargs['table'],
family
)
return ret
if 'chain' not in kwargs:
kwargs['chain'] = ''
else:
res = __salt__['nftables.check_chain'](kwargs['table'],
kwargs['chain'],
family=family)
if not res['result']:
ret['result'] = False
ret['comment'] = 'Failed to flush chain {0} in table {1} in family {2}, chain does not exist.'.format(
kwargs['chain'],
kwargs['table'],
family
)
return ret
res = __salt__['nftables.flush'](kwargs['table'],
kwargs['chain'],
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flush nftables rules in {0} table {1} chain {2} family'.format(
kwargs['table'],
kwargs['chain'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush nftables rules'
return ret
|
saltstack/salt
|
salt/states/nftables.py
|
chain_absent
|
python
|
def chain_absent(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.7.0
Verify the chain is absent.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['nftables.check_chain'](table, name, family)
if not chain_check:
ret['result'] = True
ret['comment'] = ('nftables {0} chain is already absent in {1} table for {2}'
.format(name, table, family))
return ret
flush_chain = __salt__['nftables.flush'](table, name, family)
if flush_chain:
command = __salt__['nftables.delete_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('nftables {0} chain in {1} table delete success for {2}'
.format(name, table, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
.format(name, table, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
name,
table,
flush_chain.strip(),
family
)
return ret
|
.. versionadded:: 2014.7.0
Verify the chain is absent.
family
Networking family, either ipv4 or ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nftables.py#L183-L225
| null |
# -*- coding: utf-8 -*-
'''
Management of nftables
======================
This is an nftables-specific module designed to manage Linux firewalls. It is
expected that this state module, and other system-specific firewall states, may
at some point be deprecated in favor of a more generic `firewall` state.
.. code-block:: yaml
httpd:
nftables.append:
- table: filter
- chain: input
- jump: accept
- match: state
- connstate: new
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.append:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.insert:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.insert:
- position: 1
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
output:
nftables.chain_present:
- family: ip
- table: filter
output:
nftables.chain_absent:
- family: ip
- table: filter
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if the locale module is available in __salt__
'''
return 'nftables' if 'nftables.version' in __salt__ else False
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['nftables.check_chain'](table, name, family=family)
if chain_check['result'] is True:
ret['result'] = True
ret['comment'] = ('nftables {0} chain is already exist in {1} table for {2}'
.format(name, table, family))
return ret
res = __salt__['nftables.new_chain'](
table,
name,
table_type=table_type,
hook=hook,
priority=priority,
family=family
)
if res['result'] is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('nftables {0} chain in {1} table create success for {2}'
.format(name, table, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
name,
table,
res['comment'].strip(),
family
)
return ret
def append(name, family='ipv4', **kwargs):
'''
.. versionadded:: 0.17.0
Append a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True, family=family, command='add', **kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
res = __salt__['nftables.append'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Set and Saved nftables rule for {0} to: '
'{1} for {2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set nftables rule for {0}.\n'
'Attempted rule was {1} for {2}.\n'
'{3}').format(
name,
command.strip(), family, res['comment'])
return ret
def insert(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True,
family=family,
command='insert',
**kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
res = __salt__['nftables.insert'](kwargs['table'],
kwargs['chain'],
kwargs['position'],
rule,
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Set and Saved nftables rule for {0} to: '
'{1} for {2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set nftables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def delete(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True, family=family, command='D', **kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if not res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already absent for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be deleted for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'position' in kwargs:
res = __salt__['nftables.delete'](
kwargs['table'],
kwargs['chain'],
family=family,
position=kwargs['position'])
else:
res = __salt__['nftables.delete'](
kwargs['table'],
kwargs['chain'],
family=family,
rule=rule)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Delete nftables rule for {0} {1}'.format(
name,
command.strip())
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Deleted and Saved nftables rule for {0} for {1}'
'{2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to delete nftables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def flush(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Flush current nftables state
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if 'table' not in kwargs:
kwargs['table'] = 'filter'
res = __salt__['nftables.check_table'](kwargs['table'], family=family)
if not res['result']:
ret['result'] = False
ret['comment'] = 'Failed to flush table {0} in family {1}, table does not exist.'.format(
kwargs['table'],
family
)
return ret
if 'chain' not in kwargs:
kwargs['chain'] = ''
else:
res = __salt__['nftables.check_chain'](kwargs['table'],
kwargs['chain'],
family=family)
if not res['result']:
ret['result'] = False
ret['comment'] = 'Failed to flush chain {0} in table {1} in family {2}, chain does not exist.'.format(
kwargs['chain'],
kwargs['table'],
family
)
return ret
res = __salt__['nftables.flush'](kwargs['table'],
kwargs['chain'],
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flush nftables rules in {0} table {1} chain {2} family'.format(
kwargs['table'],
kwargs['chain'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush nftables rules'
return ret
|
saltstack/salt
|
salt/states/nftables.py
|
append
|
python
|
def append(name, family='ipv4', **kwargs):
'''
.. versionadded:: 0.17.0
Append a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True, family=family, command='add', **kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
res = __salt__['nftables.append'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Set and Saved nftables rule for {0} to: '
'{1} for {2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set nftables rule for {0}.\n'
'Attempted rule was {1} for {2}.\n'
'{3}').format(
name,
command.strip(), family, res['comment'])
return ret
|
.. versionadded:: 0.17.0
Append a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nftables.py#L228-L305
| null |
# -*- coding: utf-8 -*-
'''
Management of nftables
======================
This is an nftables-specific module designed to manage Linux firewalls. It is
expected that this state module, and other system-specific firewall states, may
at some point be deprecated in favor of a more generic `firewall` state.
.. code-block:: yaml
httpd:
nftables.append:
- table: filter
- chain: input
- jump: accept
- match: state
- connstate: new
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.append:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.insert:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.insert:
- position: 1
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
output:
nftables.chain_present:
- family: ip
- table: filter
output:
nftables.chain_absent:
- family: ip
- table: filter
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if the locale module is available in __salt__
'''
return 'nftables' if 'nftables.version' in __salt__ else False
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['nftables.check_chain'](table, name, family=family)
if chain_check['result'] is True:
ret['result'] = True
ret['comment'] = ('nftables {0} chain is already exist in {1} table for {2}'
.format(name, table, family))
return ret
res = __salt__['nftables.new_chain'](
table,
name,
table_type=table_type,
hook=hook,
priority=priority,
family=family
)
if res['result'] is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('nftables {0} chain in {1} table create success for {2}'
.format(name, table, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
name,
table,
res['comment'].strip(),
family
)
return ret
def chain_absent(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.7.0
Verify the chain is absent.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['nftables.check_chain'](table, name, family)
if not chain_check:
ret['result'] = True
ret['comment'] = ('nftables {0} chain is already absent in {1} table for {2}'
.format(name, table, family))
return ret
flush_chain = __salt__['nftables.flush'](table, name, family)
if flush_chain:
command = __salt__['nftables.delete_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('nftables {0} chain in {1} table delete success for {2}'
.format(name, table, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
.format(name, table, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
name,
table,
flush_chain.strip(),
family
)
return ret
def insert(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True,
family=family,
command='insert',
**kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
res = __salt__['nftables.insert'](kwargs['table'],
kwargs['chain'],
kwargs['position'],
rule,
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Set and Saved nftables rule for {0} to: '
'{1} for {2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set nftables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def delete(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True, family=family, command='D', **kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if not res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already absent for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be deleted for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'position' in kwargs:
res = __salt__['nftables.delete'](
kwargs['table'],
kwargs['chain'],
family=family,
position=kwargs['position'])
else:
res = __salt__['nftables.delete'](
kwargs['table'],
kwargs['chain'],
family=family,
rule=rule)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Delete nftables rule for {0} {1}'.format(
name,
command.strip())
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Deleted and Saved nftables rule for {0} for {1}'
'{2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to delete nftables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def flush(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Flush current nftables state
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if 'table' not in kwargs:
kwargs['table'] = 'filter'
res = __salt__['nftables.check_table'](kwargs['table'], family=family)
if not res['result']:
ret['result'] = False
ret['comment'] = 'Failed to flush table {0} in family {1}, table does not exist.'.format(
kwargs['table'],
family
)
return ret
if 'chain' not in kwargs:
kwargs['chain'] = ''
else:
res = __salt__['nftables.check_chain'](kwargs['table'],
kwargs['chain'],
family=family)
if not res['result']:
ret['result'] = False
ret['comment'] = 'Failed to flush chain {0} in table {1} in family {2}, chain does not exist.'.format(
kwargs['chain'],
kwargs['table'],
family
)
return ret
res = __salt__['nftables.flush'](kwargs['table'],
kwargs['chain'],
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flush nftables rules in {0} table {1} chain {2} family'.format(
kwargs['table'],
kwargs['chain'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush nftables rules'
return ret
|
saltstack/salt
|
salt/states/nftables.py
|
flush
|
python
|
def flush(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Flush current nftables state
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if 'table' not in kwargs:
kwargs['table'] = 'filter'
res = __salt__['nftables.check_table'](kwargs['table'], family=family)
if not res['result']:
ret['result'] = False
ret['comment'] = 'Failed to flush table {0} in family {1}, table does not exist.'.format(
kwargs['table'],
family
)
return ret
if 'chain' not in kwargs:
kwargs['chain'] = ''
else:
res = __salt__['nftables.check_chain'](kwargs['table'],
kwargs['chain'],
family=family)
if not res['result']:
ret['result'] = False
ret['comment'] = 'Failed to flush chain {0} in table {1} in family {2}, chain does not exist.'.format(
kwargs['chain'],
kwargs['table'],
family
)
return ret
res = __salt__['nftables.flush'](kwargs['table'],
kwargs['chain'],
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flush nftables rules in {0} table {1} chain {2} family'.format(
kwargs['table'],
kwargs['chain'],
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush nftables rules'
return ret
|
.. versionadded:: 2014.7.0
Flush current nftables state
family
Networking family, either ipv4 or ipv6
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nftables.py#L480-L541
| null |
# -*- coding: utf-8 -*-
'''
Management of nftables
======================
This is an nftables-specific module designed to manage Linux firewalls. It is
expected that this state module, and other system-specific firewall states, may
at some point be deprecated in favor of a more generic `firewall` state.
.. code-block:: yaml
httpd:
nftables.append:
- table: filter
- chain: input
- jump: accept
- match: state
- connstate: new
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.append:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.insert:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.insert:
- position: 1
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- position: 1
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
httpd:
nftables.delete:
- table: filter
- family: ipv6
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: NEW
- dport: 80
- proto: tcp
- sport: 1025:65535
- save: True
output:
nftables.chain_present:
- family: ip
- table: filter
output:
nftables.chain_absent:
- family: ip
- table: filter
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS
import logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if the locale module is available in __salt__
'''
return 'nftables' if 'nftables.version' in __salt__ else False
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'):
'''
.. versionadded:: 2014.7.0
Verify the chain is exist.
name
A user-defined chain name.
table
The table to own the chain.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['nftables.check_chain'](table, name, family=family)
if chain_check['result'] is True:
ret['result'] = True
ret['comment'] = ('nftables {0} chain is already exist in {1} table for {2}'
.format(name, table, family))
return ret
res = __salt__['nftables.new_chain'](
table,
name,
table_type=table_type,
hook=hook,
priority=priority,
family=family
)
if res['result'] is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('nftables {0} chain in {1} table create success for {2}'
.format(name, table, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
name,
table,
res['comment'].strip(),
family
)
return ret
def chain_absent(name, table='filter', family='ipv4'):
'''
.. versionadded:: 2014.7.0
Verify the chain is absent.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
chain_check = __salt__['nftables.check_chain'](table, name, family)
if not chain_check:
ret['result'] = True
ret['comment'] = ('nftables {0} chain is already absent in {1} table for {2}'
.format(name, table, family))
return ret
flush_chain = __salt__['nftables.flush'](table, name, family)
if flush_chain:
command = __salt__['nftables.delete_chain'](table, name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('nftables {0} chain in {1} table delete success for {2}'
.format(name, table, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete {0} chain in {1} table: {2} for {3}'
.format(name, table, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush {0} chain in {1} table: {2} for {3}'.format(
name,
table,
flush_chain.strip(),
family
)
return ret
def append(name, family='ipv4', **kwargs):
'''
.. versionadded:: 0.17.0
Append a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Network family, ipv4 or ipv6.
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True, family=family, command='add', **kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be set ({1}) for {2}'.format(
name,
command.strip(),
family)
return ret
res = __salt__['nftables.append'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Set and Saved nftables rule for {0} to: '
'{1} for {2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set nftables rule for {0}.\n'
'Attempted rule was {1} for {2}.\n'
'{3}').format(
name,
command.strip(), family, res['comment'])
return ret
def insert(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True,
family=family,
command='insert',
**kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be set for {1} ({2})'.format(
name,
family,
command.strip())
return ret
res = __salt__['nftables.insert'](kwargs['table'],
kwargs['chain'],
kwargs['position'],
rule,
family)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Set nftables rule for {0} to: {1} for {2}'.format(
name,
command.strip(),
family)
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Set and Saved nftables rule for {0} to: '
'{1} for {2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to set nftables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
def delete(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Delete a rule to a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
family
Networking family, either ipv4 or ipv6
All other arguments are passed in with the same name as the long option
that would normally be used for nftables, with one exception: `--state` is
specified as `connstate` instead of `state` (not to be confused with
`ctstate`).
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
res = __salt__['nftables.build_rule'](family=family, **kwargs)
if not res['result']:
return res
rule = res['rule']
res = __salt__['nftables.build_rule'](full=True, family=family, command='D', **kwargs)
if not res['result']:
return res
command = res['rule']
res = __salt__['nftables.check'](kwargs['table'],
kwargs['chain'],
rule,
family)
if not res['result']:
ret['result'] = True
ret['comment'] = 'nftables rule for {0} already absent for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'test' in __opts__ and __opts__['test']:
ret['comment'] = 'nftables rule for {0} needs to be deleted for {1} ({2})'.format(
name,
family,
command.strip())
return ret
if 'position' in kwargs:
res = __salt__['nftables.delete'](
kwargs['table'],
kwargs['chain'],
family=family,
position=kwargs['position'])
else:
res = __salt__['nftables.delete'](
kwargs['table'],
kwargs['chain'],
family=family,
rule=rule)
if res['result']:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Delete nftables rule for {0} {1}'.format(
name,
command.strip())
if 'save' in kwargs:
if kwargs['save']:
__salt__['nftables.save'](filename=None, family=family)
ret['comment'] = ('Deleted and Saved nftables rule for {0} for {1}'
'{2}'.format(name, command.strip(), family))
return ret
else:
ret['result'] = False
ret['comment'] = ('Failed to delete nftables rule for {0}.\n'
'Attempted rule was {1}').format(
name,
command.strip())
return ret
|
saltstack/salt
|
salt/modules/riak.py
|
__execute_cmd
|
python
|
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
)
|
Execute Riak commands
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L20-L26
| null |
# -*- coding: utf-8 -*-
'''
Riak Salt Module
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only available on systems with Riak installed.
'''
if salt.utils.path.which('riak'):
return True
return (False, 'The riak execution module failed to load: the riak binary is not in the path.')
def start():
'''
Start Riak
CLI Example:
.. code-block:: bash
salt '*' riak.start
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'start')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def stop():
'''
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'stop')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_join(username, hostname):
'''
Join a Riak cluster
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_join <user> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster join {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_leave(username, hostname):
'''
Leave a Riak cluster
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_leave <username> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster leave {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_plan():
'''
Review Cluster Plan
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_plan
'''
cmd = __execute_cmd('riak-admin', 'cluster plan')
if cmd['retcode'] != 0:
return False
return True
def cluster_commit():
'''
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'cluster commit')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def member_status():
'''
Get cluster member status
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.member_status
'''
ret = {'membership': {},
'summary': {'Valid': 0,
'Leaving': 0,
'Exiting': 0,
'Joining': 0,
'Down': 0,
}}
out = __execute_cmd('riak-admin', 'member-status')['stdout'].splitlines()
for line in out:
if line.startswith(('=', '-', 'Status')):
continue
if '/' in line:
# We're in the summary line
for item in line.split('/'):
key, val = item.split(':')
ret['summary'][key.strip()] = val.strip()
if len(line.split()) == 4:
# We're on a node status line
(status, ring, pending, node) = line.split()
ret['membership'][node] = {
'Status': status,
'Ring': ring,
'Pending': pending
}
return ret
def status():
'''
Current node status
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.status
'''
ret = {}
cmd = __execute_cmd('riak-admin', 'status')
for i in cmd['stdout'].splitlines():
if ':' in i:
(name, val) = i.split(':', 1)
ret[name.strip()] = val.strip()
return ret
def test():
'''
Runs a test of a few standard Riak operations
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.test
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'test')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def services():
'''
List available services on a node
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.services
'''
cmd = __execute_cmd('riak-admin', 'services')
return cmd['stdout'][1:-1].split(',')
|
saltstack/salt
|
salt/modules/riak.py
|
start
|
python
|
def start():
'''
Start Riak
CLI Example:
.. code-block:: bash
salt '*' riak.start
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'start')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
|
Start Riak
CLI Example:
.. code-block:: bash
salt '*' riak.start
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L29-L49
|
[
"def __execute_cmd(name, cmd):\n '''\n Execute Riak commands\n '''\n return __salt__['cmd.run_all'](\n '{0} {1}'.format(salt.utils.path.which(name), cmd)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Riak Salt Module
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only available on systems with Riak installed.
'''
if salt.utils.path.which('riak'):
return True
return (False, 'The riak execution module failed to load: the riak binary is not in the path.')
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
)
def stop():
'''
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'stop')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_join(username, hostname):
'''
Join a Riak cluster
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_join <user> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster join {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_leave(username, hostname):
'''
Leave a Riak cluster
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_leave <username> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster leave {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_plan():
'''
Review Cluster Plan
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_plan
'''
cmd = __execute_cmd('riak-admin', 'cluster plan')
if cmd['retcode'] != 0:
return False
return True
def cluster_commit():
'''
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'cluster commit')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def member_status():
'''
Get cluster member status
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.member_status
'''
ret = {'membership': {},
'summary': {'Valid': 0,
'Leaving': 0,
'Exiting': 0,
'Joining': 0,
'Down': 0,
}}
out = __execute_cmd('riak-admin', 'member-status')['stdout'].splitlines()
for line in out:
if line.startswith(('=', '-', 'Status')):
continue
if '/' in line:
# We're in the summary line
for item in line.split('/'):
key, val = item.split(':')
ret['summary'][key.strip()] = val.strip()
if len(line.split()) == 4:
# We're on a node status line
(status, ring, pending, node) = line.split()
ret['membership'][node] = {
'Status': status,
'Ring': ring,
'Pending': pending
}
return ret
def status():
'''
Current node status
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.status
'''
ret = {}
cmd = __execute_cmd('riak-admin', 'status')
for i in cmd['stdout'].splitlines():
if ':' in i:
(name, val) = i.split(':', 1)
ret[name.strip()] = val.strip()
return ret
def test():
'''
Runs a test of a few standard Riak operations
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.test
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'test')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def services():
'''
List available services on a node
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.services
'''
cmd = __execute_cmd('riak-admin', 'services')
return cmd['stdout'][1:-1].split(',')
|
saltstack/salt
|
salt/modules/riak.py
|
stop
|
python
|
def stop():
'''
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'stop')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
|
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L52-L74
|
[
"def __execute_cmd(name, cmd):\n '''\n Execute Riak commands\n '''\n return __salt__['cmd.run_all'](\n '{0} {1}'.format(salt.utils.path.which(name), cmd)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Riak Salt Module
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only available on systems with Riak installed.
'''
if salt.utils.path.which('riak'):
return True
return (False, 'The riak execution module failed to load: the riak binary is not in the path.')
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
)
def start():
'''
Start Riak
CLI Example:
.. code-block:: bash
salt '*' riak.start
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'start')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_join(username, hostname):
'''
Join a Riak cluster
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_join <user> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster join {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_leave(username, hostname):
'''
Leave a Riak cluster
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_leave <username> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster leave {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_plan():
'''
Review Cluster Plan
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_plan
'''
cmd = __execute_cmd('riak-admin', 'cluster plan')
if cmd['retcode'] != 0:
return False
return True
def cluster_commit():
'''
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'cluster commit')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def member_status():
'''
Get cluster member status
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.member_status
'''
ret = {'membership': {},
'summary': {'Valid': 0,
'Leaving': 0,
'Exiting': 0,
'Joining': 0,
'Down': 0,
}}
out = __execute_cmd('riak-admin', 'member-status')['stdout'].splitlines()
for line in out:
if line.startswith(('=', '-', 'Status')):
continue
if '/' in line:
# We're in the summary line
for item in line.split('/'):
key, val = item.split(':')
ret['summary'][key.strip()] = val.strip()
if len(line.split()) == 4:
# We're on a node status line
(status, ring, pending, node) = line.split()
ret['membership'][node] = {
'Status': status,
'Ring': ring,
'Pending': pending
}
return ret
def status():
'''
Current node status
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.status
'''
ret = {}
cmd = __execute_cmd('riak-admin', 'status')
for i in cmd['stdout'].splitlines():
if ':' in i:
(name, val) = i.split(':', 1)
ret[name.strip()] = val.strip()
return ret
def test():
'''
Runs a test of a few standard Riak operations
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.test
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'test')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def services():
'''
List available services on a node
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.services
'''
cmd = __execute_cmd('riak-admin', 'services')
return cmd['stdout'][1:-1].split(',')
|
saltstack/salt
|
salt/modules/riak.py
|
cluster_join
|
python
|
def cluster_join(username, hostname):
'''
Join a Riak cluster
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_join <user> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster join {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
|
Join a Riak cluster
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_join <user> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L77-L104
|
[
"def __execute_cmd(name, cmd):\n '''\n Execute Riak commands\n '''\n return __salt__['cmd.run_all'](\n '{0} {1}'.format(salt.utils.path.which(name), cmd)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Riak Salt Module
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only available on systems with Riak installed.
'''
if salt.utils.path.which('riak'):
return True
return (False, 'The riak execution module failed to load: the riak binary is not in the path.')
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
)
def start():
'''
Start Riak
CLI Example:
.. code-block:: bash
salt '*' riak.start
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'start')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def stop():
'''
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'stop')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_leave(username, hostname):
'''
Leave a Riak cluster
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_leave <username> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster leave {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_plan():
'''
Review Cluster Plan
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_plan
'''
cmd = __execute_cmd('riak-admin', 'cluster plan')
if cmd['retcode'] != 0:
return False
return True
def cluster_commit():
'''
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'cluster commit')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def member_status():
'''
Get cluster member status
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.member_status
'''
ret = {'membership': {},
'summary': {'Valid': 0,
'Leaving': 0,
'Exiting': 0,
'Joining': 0,
'Down': 0,
}}
out = __execute_cmd('riak-admin', 'member-status')['stdout'].splitlines()
for line in out:
if line.startswith(('=', '-', 'Status')):
continue
if '/' in line:
# We're in the summary line
for item in line.split('/'):
key, val = item.split(':')
ret['summary'][key.strip()] = val.strip()
if len(line.split()) == 4:
# We're on a node status line
(status, ring, pending, node) = line.split()
ret['membership'][node] = {
'Status': status,
'Ring': ring,
'Pending': pending
}
return ret
def status():
'''
Current node status
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.status
'''
ret = {}
cmd = __execute_cmd('riak-admin', 'status')
for i in cmd['stdout'].splitlines():
if ':' in i:
(name, val) = i.split(':', 1)
ret[name.strip()] = val.strip()
return ret
def test():
'''
Runs a test of a few standard Riak operations
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.test
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'test')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def services():
'''
List available services on a node
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.services
'''
cmd = __execute_cmd('riak-admin', 'services')
return cmd['stdout'][1:-1].split(',')
|
saltstack/salt
|
salt/modules/riak.py
|
cluster_commit
|
python
|
def cluster_commit():
'''
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'cluster commit')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
|
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L157-L179
|
[
"def __execute_cmd(name, cmd):\n '''\n Execute Riak commands\n '''\n return __salt__['cmd.run_all'](\n '{0} {1}'.format(salt.utils.path.which(name), cmd)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Riak Salt Module
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only available on systems with Riak installed.
'''
if salt.utils.path.which('riak'):
return True
return (False, 'The riak execution module failed to load: the riak binary is not in the path.')
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
)
def start():
'''
Start Riak
CLI Example:
.. code-block:: bash
salt '*' riak.start
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'start')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def stop():
'''
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'stop')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_join(username, hostname):
'''
Join a Riak cluster
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_join <user> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster join {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_leave(username, hostname):
'''
Leave a Riak cluster
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_leave <username> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster leave {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_plan():
'''
Review Cluster Plan
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_plan
'''
cmd = __execute_cmd('riak-admin', 'cluster plan')
if cmd['retcode'] != 0:
return False
return True
def member_status():
'''
Get cluster member status
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.member_status
'''
ret = {'membership': {},
'summary': {'Valid': 0,
'Leaving': 0,
'Exiting': 0,
'Joining': 0,
'Down': 0,
}}
out = __execute_cmd('riak-admin', 'member-status')['stdout'].splitlines()
for line in out:
if line.startswith(('=', '-', 'Status')):
continue
if '/' in line:
# We're in the summary line
for item in line.split('/'):
key, val = item.split(':')
ret['summary'][key.strip()] = val.strip()
if len(line.split()) == 4:
# We're on a node status line
(status, ring, pending, node) = line.split()
ret['membership'][node] = {
'Status': status,
'Ring': ring,
'Pending': pending
}
return ret
def status():
'''
Current node status
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.status
'''
ret = {}
cmd = __execute_cmd('riak-admin', 'status')
for i in cmd['stdout'].splitlines():
if ':' in i:
(name, val) = i.split(':', 1)
ret[name.strip()] = val.strip()
return ret
def test():
'''
Runs a test of a few standard Riak operations
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.test
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'test')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def services():
'''
List available services on a node
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.services
'''
cmd = __execute_cmd('riak-admin', 'services')
return cmd['stdout'][1:-1].split(',')
|
saltstack/salt
|
salt/modules/riak.py
|
member_status
|
python
|
def member_status():
'''
Get cluster member status
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.member_status
'''
ret = {'membership': {},
'summary': {'Valid': 0,
'Leaving': 0,
'Exiting': 0,
'Joining': 0,
'Down': 0,
}}
out = __execute_cmd('riak-admin', 'member-status')['stdout'].splitlines()
for line in out:
if line.startswith(('=', '-', 'Status')):
continue
if '/' in line:
# We're in the summary line
for item in line.split('/'):
key, val = item.split(':')
ret['summary'][key.strip()] = val.strip()
if len(line.split()) == 4:
# We're on a node status line
(status, ring, pending, node) = line.split()
ret['membership'][node] = {
'Status': status,
'Ring': ring,
'Pending': pending
}
return ret
|
Get cluster member status
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.member_status
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L182-L223
|
[
"def __execute_cmd(name, cmd):\n '''\n Execute Riak commands\n '''\n return __salt__['cmd.run_all'](\n '{0} {1}'.format(salt.utils.path.which(name), cmd)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Riak Salt Module
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only available on systems with Riak installed.
'''
if salt.utils.path.which('riak'):
return True
return (False, 'The riak execution module failed to load: the riak binary is not in the path.')
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
)
def start():
'''
Start Riak
CLI Example:
.. code-block:: bash
salt '*' riak.start
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'start')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def stop():
'''
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'stop')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_join(username, hostname):
'''
Join a Riak cluster
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_join <user> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster join {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_leave(username, hostname):
'''
Leave a Riak cluster
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_leave <username> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster leave {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_plan():
'''
Review Cluster Plan
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_plan
'''
cmd = __execute_cmd('riak-admin', 'cluster plan')
if cmd['retcode'] != 0:
return False
return True
def cluster_commit():
'''
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'cluster commit')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def status():
'''
Current node status
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.status
'''
ret = {}
cmd = __execute_cmd('riak-admin', 'status')
for i in cmd['stdout'].splitlines():
if ':' in i:
(name, val) = i.split(':', 1)
ret[name.strip()] = val.strip()
return ret
def test():
'''
Runs a test of a few standard Riak operations
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.test
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'test')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def services():
'''
List available services on a node
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.services
'''
cmd = __execute_cmd('riak-admin', 'services')
return cmd['stdout'][1:-1].split(',')
|
saltstack/salt
|
salt/modules/riak.py
|
status
|
python
|
def status():
'''
Current node status
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.status
'''
ret = {}
cmd = __execute_cmd('riak-admin', 'status')
for i in cmd['stdout'].splitlines():
if ':' in i:
(name, val) = i.split(':', 1)
ret[name.strip()] = val.strip()
return ret
|
Current node status
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.status
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L226-L247
|
[
"def __execute_cmd(name, cmd):\n '''\n Execute Riak commands\n '''\n return __salt__['cmd.run_all'](\n '{0} {1}'.format(salt.utils.path.which(name), cmd)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Riak Salt Module
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import salt libs
import salt.utils.path
def __virtual__():
'''
Only available on systems with Riak installed.
'''
if salt.utils.path.which('riak'):
return True
return (False, 'The riak execution module failed to load: the riak binary is not in the path.')
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
)
def start():
'''
Start Riak
CLI Example:
.. code-block:: bash
salt '*' riak.start
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'start')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def stop():
'''
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'stop')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_join(username, hostname):
'''
Join a Riak cluster
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_join <user> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster join {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_leave(username, hostname):
'''
Leave a Riak cluster
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_leave <username> <host>
username - The riak username to join the cluster
hostname - The riak hostname you are connecting to
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd(
'riak-admin', 'cluster leave {0}@{1}'.format(username, hostname)
)
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def cluster_plan():
'''
Review Cluster Plan
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_plan
'''
cmd = __execute_cmd('riak-admin', 'cluster plan')
if cmd['retcode'] != 0:
return False
return True
def cluster_commit():
'''
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'cluster commit')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def member_status():
'''
Get cluster member status
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.member_status
'''
ret = {'membership': {},
'summary': {'Valid': 0,
'Leaving': 0,
'Exiting': 0,
'Joining': 0,
'Down': 0,
}}
out = __execute_cmd('riak-admin', 'member-status')['stdout'].splitlines()
for line in out:
if line.startswith(('=', '-', 'Status')):
continue
if '/' in line:
# We're in the summary line
for item in line.split('/'):
key, val = item.split(':')
ret['summary'][key.strip()] = val.strip()
if len(line.split()) == 4:
# We're on a node status line
(status, ring, pending, node) = line.split()
ret['membership'][node] = {
'Status': status,
'Ring': ring,
'Pending': pending
}
return ret
def test():
'''
Runs a test of a few standard Riak operations
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.test
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'test')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stdout']
else:
ret['comment'] = cmd['stdout']
ret['success'] = True
return ret
def services():
'''
List available services on a node
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.services
'''
cmd = __execute_cmd('riak-admin', 'services')
return cmd['stdout'][1:-1].split(',')
|
saltstack/salt
|
salt/states/portage_config.py
|
flags
|
python
|
def flags(name,
use=None,
accept_keywords=None,
env=None,
license=None,
properties=None,
unmask=False,
mask=False):
'''
Enforce the given flags on the given package or ``DEPEND`` atom.
.. warning::
In most cases, the affected package(s) need to be rebuilt in
order to apply the changes.
name
The name of the package or its DEPEND atom
use
A list of ``USE`` flags
accept_keywords
A list of keywords to accept. ``~ARCH`` means current host arch, and will
be translated into a line without keywords
env
A list of environment files
license
A list of accepted licenses
properties
A list of additional properties
unmask
A boolean to unmask the package
mask
A boolean to mask the package
'''
ret = {'changes': {},
'comment': '',
'name': name,
'result': True}
if use:
result = _flags_helper('use', name, use, __opts__['test'])
if result['result']:
ret['changes']['use'] = result['changes']
elif result['result'] is False:
ret['result'] = False
ret['comment'] = result['comment']
return ret
if accept_keywords:
result = _flags_helper('accept_keywords', name, accept_keywords, __opts__['test'])
if result['result']:
ret['changes']['accept_keywords'] = result['changes']
elif result['result'] is False:
ret['result'] = False
ret['comment'] = result['comment']
return ret
if env:
result = _flags_helper('env', name, env, __opts__['test'])
if result['result']:
ret['changes']['env'] = result['changes']
elif result['result'] is False:
ret['result'] = False
ret['comment'] = result['comment']
return ret
if license:
result = _flags_helper('license', name, license, __opts__['test'])
if result['result']:
ret['changes']['license'] = result['changes']
elif result['result'] is False:
ret['result'] = False
ret['comment'] = result['comment']
return ret
if properties:
result = _flags_helper('properties', name, properties, __opts__['test'])
if result['result']:
ret['changes']['properties'] = result['changes']
elif result['result'] is False:
ret['result'] = False
ret['comment'] = result['comment']
return ret
if mask:
result = _mask_helper('mask', name, __opts__['test'])
if result['result']:
ret['changes']['mask'] = 'masked'
elif result['result'] is False:
ret['result'] = False
ret['comment'] = result['comment']
return ret
if unmask:
result = _mask_helper('unmask', name, __opts__['test'])
if result['result']:
ret['changes']['unmask'] = 'unmasked'
elif result['result'] is False:
ret['result'] = False
ret['comment'] = result['comment']
return ret
if __opts__['test'] and not ret['result']:
ret['result'] = None
return ret
|
Enforce the given flags on the given package or ``DEPEND`` atom.
.. warning::
In most cases, the affected package(s) need to be rebuilt in
order to apply the changes.
name
The name of the package or its DEPEND atom
use
A list of ``USE`` flags
accept_keywords
A list of keywords to accept. ``~ARCH`` means current host arch, and will
be translated into a line without keywords
env
A list of environment files
license
A list of accepted licenses
properties
A list of additional properties
unmask
A boolean to unmask the package
mask
A boolean to mask the package
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/portage_config.py#L63-L168
|
[
"def _flags_helper(conf, atom, new_flags, test=False):\n try:\n new_flags = __salt__['portage_config.get_missing_flags'](conf, atom, new_flags)\n except Exception:\n import traceback\n return {'result': False, 'comment': traceback.format_exc()}\n if new_flags:\n old_flags = __salt__['portage_config.get_flags_from_package_conf'](conf, atom)\n if not test:\n __salt__['portage_config.append_to_package_conf'](conf, atom, new_flags)\n return {'result': True, 'changes': {'old': old_flags, 'new': new_flags}}\n return {'result': None}\n",
"def _mask_helper(conf, atom, test=False):\n try:\n is_present = __salt__['portage_config.is_present'](conf, atom)\n except Exception:\n import traceback\n return {'result': False, 'comment': traceback.format_exc()}\n if not is_present:\n if not test:\n __salt__['portage_config.append_to_package_conf'](conf, string=atom)\n return {'result': True}\n return {'result': None}\n"
] |
# -*- coding: utf-8 -*-
'''
Management of Portage package configuration on Gentoo
=====================================================
A state module to manage Portage configuration on Gentoo
.. code-block:: yaml
salt:
portage_config.flags:
- use:
- openssl
'''
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only load if the portage_config module is available in __salt__
'''
return 'portage_config' if 'portage_config.get_missing_flags' in __salt__ else False
def mod_init(low):
'''
Enforce a nice structure on the configuration files.
'''
try:
__salt__['portage_config.enforce_nice_config']()
except Exception:
return False
return True
def _flags_helper(conf, atom, new_flags, test=False):
try:
new_flags = __salt__['portage_config.get_missing_flags'](conf, atom, new_flags)
except Exception:
import traceback
return {'result': False, 'comment': traceback.format_exc()}
if new_flags:
old_flags = __salt__['portage_config.get_flags_from_package_conf'](conf, atom)
if not test:
__salt__['portage_config.append_to_package_conf'](conf, atom, new_flags)
return {'result': True, 'changes': {'old': old_flags, 'new': new_flags}}
return {'result': None}
def _mask_helper(conf, atom, test=False):
try:
is_present = __salt__['portage_config.is_present'](conf, atom)
except Exception:
import traceback
return {'result': False, 'comment': traceback.format_exc()}
if not is_present:
if not test:
__salt__['portage_config.append_to_package_conf'](conf, string=atom)
return {'result': True}
return {'result': None}
|
saltstack/salt
|
salt/modules/webutil.py
|
useradd
|
python
|
def useradd(pwfile, user, password, opts='', runas=None):
'''
Add a user to htpasswd file using the htpasswd command. If the htpasswd
file does not exist, it will be created.
pwfile
Path to htpasswd file
user
User name
password
User password
opts
Valid options that can be passed are:
- `n` Don't update file; display results on stdout.
- `m` Force MD5 encryption of the password (default).
- `d` Force CRYPT encryption of the password.
- `p` Do not encrypt the password (plaintext).
- `s` Force SHA encryption of the password.
runas
The system user to run htpasswd command with
CLI Examples:
.. code-block:: bash
salt '*' webutil.useradd /etc/httpd/htpasswd larry badpassword
salt '*' webutil.useradd /etc/httpd/htpasswd larry badpass opts=ns
'''
if not os.path.exists(pwfile):
opts += 'c'
cmd = ['htpasswd', '-b{0}'.format(opts), pwfile, user, password]
return __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
|
Add a user to htpasswd file using the htpasswd command. If the htpasswd
file does not exist, it will be created.
pwfile
Path to htpasswd file
user
User name
password
User password
opts
Valid options that can be passed are:
- `n` Don't update file; display results on stdout.
- `m` Force MD5 encryption of the password (default).
- `d` Force CRYPT encryption of the password.
- `p` Do not encrypt the password (plaintext).
- `s` Force SHA encryption of the password.
runas
The system user to run htpasswd command with
CLI Examples:
.. code-block:: bash
salt '*' webutil.useradd /etc/httpd/htpasswd larry badpassword
salt '*' webutil.useradd /etc/httpd/htpasswd larry badpass opts=ns
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/webutil.py#L33-L70
| null |
# -*- coding: utf-8 -*-
'''
Support for htpasswd command. Requires the apache2-utils package for Debian-based distros.
.. versionadded:: 2014.1.0
The functions here will load inside the webutil module. This allows other
functions that don't use htpasswd to use the webutil module name.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
__virtualname__ = 'webutil'
def __virtual__():
'''
Only load the module if htpasswd is installed
'''
if salt.utils.path.which('htpasswd'):
return __virtualname__
return (False, 'The htpasswd execution mdule cannot be loaded: htpasswd binary not in path.')
def userdel(pwfile, user, runas=None, all_results=False):
'''
Delete a user from the specified htpasswd file.
pwfile
Path to htpasswd file
user
User name
runas
The system user to run htpasswd command with
all_results
Return stdout, stderr, and retcode, not just stdout
CLI Examples:
.. code-block:: bash
salt '*' webutil.userdel /etc/httpd/htpasswd larry
'''
if not os.path.exists(pwfile):
return 'Error: The specified htpasswd file does not exist'
cmd = ['htpasswd', '-D', pwfile, user]
if all_results:
out = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
else:
out = __salt__['cmd.run'](cmd, runas=runas,
python_shell=False).splitlines()
return out
def verify(pwfile, user, password, opts='', runas=None):
'''
Return True if the htpasswd file exists, the user has an entry, and their
password matches.
pwfile
Fully qualified path to htpasswd file
user
User name
password
User password
opts
Valid options that can be passed are:
- `m` Force MD5 encryption of the password (default).
- `d` Force CRYPT encryption of the password.
- `p` Do not encrypt the password (plaintext).
- `s` Force SHA encryption of the password.
runas
The system user to run htpasswd command with
CLI Examples:
.. code-block:: bash
salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword
salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword opts=ns
'''
if not os.path.exists(pwfile):
return False
cmd = ['htpasswd', '-bv{0}'.format(opts), pwfile, user, password]
ret = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
log.debug('Result of verifying htpasswd for user %s: %s', user, ret)
return ret['retcode'] == 0
|
saltstack/salt
|
salt/modules/webutil.py
|
userdel
|
python
|
def userdel(pwfile, user, runas=None, all_results=False):
'''
Delete a user from the specified htpasswd file.
pwfile
Path to htpasswd file
user
User name
runas
The system user to run htpasswd command with
all_results
Return stdout, stderr, and retcode, not just stdout
CLI Examples:
.. code-block:: bash
salt '*' webutil.userdel /etc/httpd/htpasswd larry
'''
if not os.path.exists(pwfile):
return 'Error: The specified htpasswd file does not exist'
cmd = ['htpasswd', '-D', pwfile, user]
if all_results:
out = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
else:
out = __salt__['cmd.run'](cmd, runas=runas,
python_shell=False).splitlines()
return out
|
Delete a user from the specified htpasswd file.
pwfile
Path to htpasswd file
user
User name
runas
The system user to run htpasswd command with
all_results
Return stdout, stderr, and retcode, not just stdout
CLI Examples:
.. code-block:: bash
salt '*' webutil.userdel /etc/httpd/htpasswd larry
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/webutil.py#L73-L106
| null |
# -*- coding: utf-8 -*-
'''
Support for htpasswd command. Requires the apache2-utils package for Debian-based distros.
.. versionadded:: 2014.1.0
The functions here will load inside the webutil module. This allows other
functions that don't use htpasswd to use the webutil module name.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
__virtualname__ = 'webutil'
def __virtual__():
'''
Only load the module if htpasswd is installed
'''
if salt.utils.path.which('htpasswd'):
return __virtualname__
return (False, 'The htpasswd execution mdule cannot be loaded: htpasswd binary not in path.')
def useradd(pwfile, user, password, opts='', runas=None):
'''
Add a user to htpasswd file using the htpasswd command. If the htpasswd
file does not exist, it will be created.
pwfile
Path to htpasswd file
user
User name
password
User password
opts
Valid options that can be passed are:
- `n` Don't update file; display results on stdout.
- `m` Force MD5 encryption of the password (default).
- `d` Force CRYPT encryption of the password.
- `p` Do not encrypt the password (plaintext).
- `s` Force SHA encryption of the password.
runas
The system user to run htpasswd command with
CLI Examples:
.. code-block:: bash
salt '*' webutil.useradd /etc/httpd/htpasswd larry badpassword
salt '*' webutil.useradd /etc/httpd/htpasswd larry badpass opts=ns
'''
if not os.path.exists(pwfile):
opts += 'c'
cmd = ['htpasswd', '-b{0}'.format(opts), pwfile, user, password]
return __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
def verify(pwfile, user, password, opts='', runas=None):
'''
Return True if the htpasswd file exists, the user has an entry, and their
password matches.
pwfile
Fully qualified path to htpasswd file
user
User name
password
User password
opts
Valid options that can be passed are:
- `m` Force MD5 encryption of the password (default).
- `d` Force CRYPT encryption of the password.
- `p` Do not encrypt the password (plaintext).
- `s` Force SHA encryption of the password.
runas
The system user to run htpasswd command with
CLI Examples:
.. code-block:: bash
salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword
salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword opts=ns
'''
if not os.path.exists(pwfile):
return False
cmd = ['htpasswd', '-bv{0}'.format(opts), pwfile, user, password]
ret = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
log.debug('Result of verifying htpasswd for user %s: %s', user, ret)
return ret['retcode'] == 0
|
saltstack/salt
|
salt/modules/webutil.py
|
verify
|
python
|
def verify(pwfile, user, password, opts='', runas=None):
'''
Return True if the htpasswd file exists, the user has an entry, and their
password matches.
pwfile
Fully qualified path to htpasswd file
user
User name
password
User password
opts
Valid options that can be passed are:
- `m` Force MD5 encryption of the password (default).
- `d` Force CRYPT encryption of the password.
- `p` Do not encrypt the password (plaintext).
- `s` Force SHA encryption of the password.
runas
The system user to run htpasswd command with
CLI Examples:
.. code-block:: bash
salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword
salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword opts=ns
'''
if not os.path.exists(pwfile):
return False
cmd = ['htpasswd', '-bv{0}'.format(opts), pwfile, user, password]
ret = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
log.debug('Result of verifying htpasswd for user %s: %s', user, ret)
return ret['retcode'] == 0
|
Return True if the htpasswd file exists, the user has an entry, and their
password matches.
pwfile
Fully qualified path to htpasswd file
user
User name
password
User password
opts
Valid options that can be passed are:
- `m` Force MD5 encryption of the password (default).
- `d` Force CRYPT encryption of the password.
- `p` Do not encrypt the password (plaintext).
- `s` Force SHA encryption of the password.
runas
The system user to run htpasswd command with
CLI Examples:
.. code-block:: bash
salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword
salt '*' webutil.verify /etc/httpd/htpasswd larry maybepassword opts=ns
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/webutil.py#L109-L148
| null |
# -*- coding: utf-8 -*-
'''
Support for htpasswd command. Requires the apache2-utils package for Debian-based distros.
.. versionadded:: 2014.1.0
The functions here will load inside the webutil module. This allows other
functions that don't use htpasswd to use the webutil module name.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
# Import salt libs
import salt.utils.path
log = logging.getLogger(__name__)
__virtualname__ = 'webutil'
def __virtual__():
'''
Only load the module if htpasswd is installed
'''
if salt.utils.path.which('htpasswd'):
return __virtualname__
return (False, 'The htpasswd execution mdule cannot be loaded: htpasswd binary not in path.')
def useradd(pwfile, user, password, opts='', runas=None):
'''
Add a user to htpasswd file using the htpasswd command. If the htpasswd
file does not exist, it will be created.
pwfile
Path to htpasswd file
user
User name
password
User password
opts
Valid options that can be passed are:
- `n` Don't update file; display results on stdout.
- `m` Force MD5 encryption of the password (default).
- `d` Force CRYPT encryption of the password.
- `p` Do not encrypt the password (plaintext).
- `s` Force SHA encryption of the password.
runas
The system user to run htpasswd command with
CLI Examples:
.. code-block:: bash
salt '*' webutil.useradd /etc/httpd/htpasswd larry badpassword
salt '*' webutil.useradd /etc/httpd/htpasswd larry badpass opts=ns
'''
if not os.path.exists(pwfile):
opts += 'c'
cmd = ['htpasswd', '-b{0}'.format(opts), pwfile, user, password]
return __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
def userdel(pwfile, user, runas=None, all_results=False):
'''
Delete a user from the specified htpasswd file.
pwfile
Path to htpasswd file
user
User name
runas
The system user to run htpasswd command with
all_results
Return stdout, stderr, and retcode, not just stdout
CLI Examples:
.. code-block:: bash
salt '*' webutil.userdel /etc/httpd/htpasswd larry
'''
if not os.path.exists(pwfile):
return 'Error: The specified htpasswd file does not exist'
cmd = ['htpasswd', '-D', pwfile, user]
if all_results:
out = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
else:
out = __salt__['cmd.run'](cmd, runas=runas,
python_shell=False).splitlines()
return out
|
saltstack/salt
|
salt/utils/win_functions.py
|
is_admin
|
python
|
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
|
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L51-L68
|
[
"def get_user_groups(name, sid=False):\n '''\n Get the groups to which a user belongs\n\n Args:\n name (str): The user name to query\n sid (bool): True will return a list of SIDs, False will return a list of\n group names\n\n Returns:\n list: A list of group names or sids\n '''\n if name == 'SYSTEM':\n # 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.\n groups = [name]\n else:\n groups = win32net.NetUserGetLocalGroups(None, name)\n\n if not sid:\n return groups\n\n ret_groups = set()\n for group in groups:\n ret_groups.add(get_sid_from_name(group))\n\n return ret_groups\n"
] |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
saltstack/salt
|
salt/utils/win_functions.py
|
get_user_groups
|
python
|
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
|
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L71-L96
|
[
"def get_sid_from_name(name):\n '''\n This is a tool for getting a sid from a name. The name can be any object.\n Usually a user or a group\n\n Args:\n name (str): The name of the user or group for which to get the sid\n\n Returns:\n str: The corresponding SID\n '''\n # If None is passed, use the Universal Well-known SID \"Null SID\"\n if name is None:\n name = 'NULL SID'\n\n try:\n sid = win32security.LookupAccountName(None, name)[0]\n except pywintypes.error as exc:\n raise CommandExecutionError(\n 'User {0} not found: {1}'.format(name, exc))\n\n return win32security.ConvertSidToStringSid(sid)\n"
] |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
saltstack/salt
|
salt/utils/win_functions.py
|
get_sid_from_name
|
python
|
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
|
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L99-L120
| null |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
saltstack/salt
|
salt/utils/win_functions.py
|
get_current_user
|
python
|
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
|
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L123-L155
|
[
"def get_sid_from_name(name):\n '''\n This is a tool for getting a sid from a name. The name can be any object.\n Usually a user or a group\n\n Args:\n name (str): The name of the user or group for which to get the sid\n\n Returns:\n str: The corresponding SID\n '''\n # If None is passed, use the Universal Well-known SID \"Null SID\"\n if name is None:\n name = 'NULL SID'\n\n try:\n sid = win32security.LookupAccountName(None, name)[0]\n except pywintypes.error as exc:\n raise CommandExecutionError(\n 'User {0} not found: {1}'.format(name, exc))\n\n return win32security.ConvertSidToStringSid(sid)\n"
] |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
saltstack/salt
|
salt/utils/win_functions.py
|
get_sam_name
|
python
|
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
|
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L158-L173
| null |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
saltstack/salt
|
salt/utils/win_functions.py
|
escape_argument
|
python
|
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
|
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L185-L209
|
[
"def escape_for_cmd_exe(arg):\n '''\n Escape an argument string to be suitable to be passed to\n cmd.exe on Windows\n\n This method takes an argument that is expected to already be properly\n escaped for the receiving program to be properly parsed. This argument\n will be further escaped to pass the interpolation performed by cmd.exe\n unchanged.\n\n Any meta-characters will be escaped, removing the ability to e.g. use\n redirects or variables.\n\n Args:\n arg (str): a single command line argument to escape for cmd.exe\n\n Returns:\n str: an escaped string suitable to be passed as a program argument to cmd.exe\n '''\n meta_chars = '()%!^\"<>&|'\n meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')\n meta_map = {char: \"^{0}\".format(char) for char in meta_chars}\n\n def escape_meta_chars(m):\n char = m.group(1)\n return meta_map[char]\n\n return meta_re.sub(escape_meta_chars, arg)\n"
] |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
saltstack/salt
|
salt/utils/win_functions.py
|
escape_for_cmd_exe
|
python
|
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
|
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L212-L239
| null |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
saltstack/salt
|
salt/utils/win_functions.py
|
broadcast_setting_change
|
python
|
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
|
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L242-L308
| null |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
saltstack/salt
|
salt/utils/win_functions.py
|
guid_to_squid
|
python
|
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
|
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L311-L339
| null |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
saltstack/salt
|
salt/utils/win_functions.py
|
squid_to_guid
|
python
|
def squid_to_guid(squid):
'''
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
'''
squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$')
squid_match = squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' + \
squid_match.group(1)[::-1]+'-' + \
squid_match.group(2)[::-1]+'-' + \
squid_match.group(3)[::-1]+'-' + \
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid
|
Converts a compressed GUID (SQUID) back into a GUID
Args:
squid (str): A valid compressed GUID
Returns:
str: A valid GUID
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_functions.py#L342-L365
| null |
# -*- coding: utf-8 -*-
'''
Various functions to be used by windows during start up and to monkey patch
missing functions in other modules
'''
from __future__ import absolute_import, print_function, unicode_literals
import platform
import re
import ctypes
# Import Salt Libs
from salt.exceptions import CommandExecutionError
from salt.ext.six.moves import range
# Import 3rd Party Libs
try:
import psutil
import pywintypes
import win32api
import win32net
import win32security
from win32con import HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG
HAS_WIN32 = True
except ImportError:
HAS_WIN32 = False
# Although utils are often directly imported, it is also possible to use the
# loader.
def __virtual__():
'''
Only load if Win32 Libraries are installed
'''
if not HAS_WIN32:
return False, 'This utility requires pywin32'
return 'win_functions'
def get_parent_pid():
'''
This is a monkey patch for os.getppid. Used in:
- salt.utils.parsers
Returns:
int: The parent process id
'''
return psutil.Process().ppid()
def is_admin(name):
'''
Is the passed user a member of the Administrators group
Args:
name (str): The name to check
Returns:
bool: True if user is a member of the Administrators group, False
otherwise
'''
groups = get_user_groups(name, True)
for group in groups:
if group in ('S-1-5-32-544', 'S-1-5-18'):
return True
return False
def get_user_groups(name, sid=False):
'''
Get the groups to which a user belongs
Args:
name (str): The user name to query
sid (bool): True will return a list of SIDs, False will return a list of
group names
Returns:
list: A list of group names or sids
'''
if name == 'SYSTEM':
# 'win32net.NetUserGetLocalGroups' will fail if you pass in 'SYSTEM'.
groups = [name]
else:
groups = win32net.NetUserGetLocalGroups(None, name)
if not sid:
return groups
ret_groups = set()
for group in groups:
ret_groups.add(get_sid_from_name(group))
return ret_groups
def get_sid_from_name(name):
'''
This is a tool for getting a sid from a name. The name can be any object.
Usually a user or a group
Args:
name (str): The name of the user or group for which to get the sid
Returns:
str: The corresponding SID
'''
# If None is passed, use the Universal Well-known SID "Null SID"
if name is None:
name = 'NULL SID'
try:
sid = win32security.LookupAccountName(None, name)[0]
except pywintypes.error as exc:
raise CommandExecutionError(
'User {0} not found: {1}'.format(name, exc))
return win32security.ConvertSidToStringSid(sid)
def get_current_user(with_domain=True):
'''
Gets the user executing the process
Args:
with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash
Returns:
str: The user name
'''
try:
user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
if user_name[-1] == '$':
# Make the system account easier to identify.
# Fetch sid so as to handle other language than english
test_user = win32api.GetUserName()
if test_user == 'SYSTEM':
user_name = 'SYSTEM'
elif get_sid_from_name(test_user) == 'S-1-5-18':
user_name = 'SYSTEM'
elif not with_domain:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
raise CommandExecutionError(
'Failed to get current user: {0}'.format(exc))
if not user_name:
return False
return user_name
def get_sam_name(username):
r'''
Gets the SAM name for a user. It basically prefixes a username without a
backslash with the computer name. If the user does not exist, a SAM
compatible name will be returned using the local hostname as the domain.
i.e. salt.utils.get_same_name('Administrator') would return 'DOMAIN.COM\Administrator'
.. note:: Long computer names are truncated to 15 characters
'''
try:
sid_obj = win32security.LookupAccountName(None, username)[0]
except pywintypes.error:
return '\\'.join([platform.node()[:15].upper(), username])
username, domain, _ = win32security.LookupAccountSid(None, sid_obj)
return '\\'.join([domain, username])
def enable_ctrl_logoff_handler():
if HAS_WIN32:
ctrl_logoff_event = 5
win32api.SetConsoleCtrlHandler(
lambda event: True if event == ctrl_logoff_event else False,
1
)
def escape_argument(arg, escape=True):
'''
Escape the argument for the cmd.exe shell.
See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
First we escape the quote chars to produce a argument suitable for
CommandLineToArgvW. We don't need to do this for simple arguments.
Args:
arg (str): a single command line argument to escape for the cmd.exe shell
Kwargs:
escape (bool): True will call the escape_for_cmd_exe() function
which escapes the characters '()%!^"<>&|'. False
will not call the function and only quotes the cmd
Returns:
str: an escaped string suitable to be passed as a program argument to the cmd.exe shell
'''
if not arg or re.search(r'(["\s])', arg):
arg = '"' + arg.replace('"', r'\"') + '"'
if not escape:
return arg
return escape_for_cmd_exe(arg)
def escape_for_cmd_exe(arg):
'''
Escape an argument string to be suitable to be passed to
cmd.exe on Windows
This method takes an argument that is expected to already be properly
escaped for the receiving program to be properly parsed. This argument
will be further escaped to pass the interpolation performed by cmd.exe
unchanged.
Any meta-characters will be escaped, removing the ability to e.g. use
redirects or variables.
Args:
arg (str): a single command line argument to escape for cmd.exe
Returns:
str: an escaped string suitable to be passed as a program argument to cmd.exe
'''
meta_chars = '()%!^"<>&|'
meta_re = re.compile('(' + '|'.join(re.escape(char) for char in list(meta_chars)) + ')')
meta_map = {char: "^{0}".format(char) for char in meta_chars}
def escape_meta_chars(m):
char = m.group(1)
return meta_map[char]
return meta_re.sub(escape_meta_chars, arg)
def broadcast_setting_change(message='Environment'):
'''
Send a WM_SETTINGCHANGE Broadcast to all Windows
Args:
message (str):
A string value representing the portion of the system that has been
updated and needs to be refreshed. Default is ``Environment``. These
are some common values:
- "Environment" : to effect a change in the environment variables
- "intl" : to effect a change in locale settings
- "Policy" : to effect a change in Group Policy Settings
- a leaf node in the registry
- the name of a section in the ``Win.ini`` file
See lParam within msdn docs for
`WM_SETTINGCHANGE <https://msdn.microsoft.com/en-us/library/ms725497%28VS.85%29.aspx>`_
for more information on Broadcasting Messages.
See GWL_WNDPROC within msdn docs for
`SetWindowLong <https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx>`_
for information on how to retrieve those messages.
.. note::
This will only affect new processes that aren't launched by services. To
apply changes to the path or registry to services, the host must be
restarted. The ``salt-minion``, if running as a service, will not see
changes to the environment until the system is restarted. Services
inherit their environment from ``services.exe`` which does not respond
to messaging events. See
`MSDN Documentation <https://support.microsoft.com/en-us/help/821761/changes-that-you-make-to-environment-variables-do-not-affect-services>`_
for more information.
CLI Example:
... code-block:: python
import salt.utils.win_functions
salt.utils.win_functions.broadcast_setting_change('Environment')
'''
# Listen for messages sent by this would involve working with the
# SetWindowLong function. This can be accessed via win32gui or through
# ctypes. You can find examples on how to do this by searching for
# `Accessing WGL_WNDPROC` on the internet. Here are some examples of how
# this might work:
#
# # using win32gui
# import win32con
# import win32gui
# old_function = win32gui.SetWindowLong(window_handle, win32con.GWL_WNDPROC, new_function)
#
# # using ctypes
# import ctypes
# import win32con
# from ctypes import c_long, c_int
# user32 = ctypes.WinDLL('user32', use_last_error=True)
# WndProcType = ctypes.WINFUNCTYPE(c_int, c_long, c_int, c_int)
# new_function = WndProcType
# old_function = user32.SetWindowLongW(window_handle, win32con.GWL_WNDPROC, new_function)
broadcast_message = ctypes.create_unicode_buffer(message)
user32 = ctypes.WinDLL('user32', use_last_error=True)
result = user32.SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
broadcast_message, SMTO_ABORTIFHUNG,
5000, 0)
return result == 1
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed by
concatenating all the reversed parts without '-'.
.. Example::
Input: 2BE0FA87-5B36-43CF-95C8-C68D6673FB94
Reversed: 78AF0EB2-63B5-FC34-598C-6CD86637BF49
Final Compressed Guid: 78AF0EB263B5FC34598C6CD86637BF49
Args:
guid (str): A valid GUID
Returns:
str: A valid compressed GUID (SQUID)
'''
guid_pattern = re.compile(r'^\{(\w{8})-(\w{4})-(\w{4})-(\w\w)(\w\w)-(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)\}$')
guid_match = guid_pattern.match(guid)
squid = ''
if guid_match is not None:
for index in range(1, 12):
squid += guid_match.group(index)[::-1]
return squid
|
saltstack/salt
|
salt/runners/mine.py
|
get
|
python
|
def get(tgt, fun, tgt_type='glob'):
'''
Gathers the data from the specified minions' mine, pass in the target,
function to look up and the target type
CLI Example:
.. code-block:: bash
salt-run mine.get '*' network.interfaces
'''
ret = salt.utils.minions.mine_get(tgt, fun, tgt_type, __opts__)
return ret
|
Gathers the data from the specified minions' mine, pass in the target,
function to look up and the target type
CLI Example:
.. code-block:: bash
salt-run mine.get '*' network.interfaces
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/mine.py#L16-L28
|
[
"def mine_get(tgt, fun, tgt_type='glob', opts=None):\n '''\n Gathers the data from the specified minions' mine, pass in the target,\n function to look up and the target type\n '''\n ret = {}\n serial = salt.payload.Serial(opts)\n checker = CkMinions(opts)\n _res = checker.check_minions(\n tgt,\n tgt_type)\n minions = _res['minions']\n cache = salt.cache.factory(opts)\n\n if isinstance(fun, six.string_types):\n functions = list(set(fun.split(',')))\n _ret_dict = len(functions) > 1\n elif isinstance(fun, list):\n functions = fun\n _ret_dict = True\n else:\n return {}\n\n for minion in minions:\n mdata = cache.fetch('minions/{0}'.format(minion), 'mine')\n\n if not isinstance(mdata, dict):\n continue\n\n if not _ret_dict and functions and functions[0] in mdata:\n ret[minion] = mdata.get(functions)\n elif _ret_dict:\n for fun in functions:\n if fun in mdata:\n ret.setdefault(fun, {})[minion] = mdata.get(fun)\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
A runner to access data from the salt mine
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import logging
# Import salt libs
import salt.utils.minions
log = logging.getLevelName(__name__)
def update(tgt,
tgt_type='glob',
clear=False,
mine_functions=None):
'''
.. versionadded:: 2017.7.0
Update the mine data on a certain group of minions.
tgt
Which minions to target for the execution.
tgt_type: ``glob``
The type of ``tgt``.
clear: ``False``
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: ``False`` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under ``mine_functions`` in the
minion/master config or pillar.
CLI Example:
.. code-block:: bash
salt-run mine.update '*'
salt-run mine.update 'juniper-edges' tgt_type='nodegroup'
'''
ret = __salt__['salt.execute'](tgt,
'mine.update',
tgt_type=tgt_type,
clear=clear,
mine_functions=mine_functions)
return ret
|
saltstack/salt
|
salt/runners/mine.py
|
update
|
python
|
def update(tgt,
tgt_type='glob',
clear=False,
mine_functions=None):
'''
.. versionadded:: 2017.7.0
Update the mine data on a certain group of minions.
tgt
Which minions to target for the execution.
tgt_type: ``glob``
The type of ``tgt``.
clear: ``False``
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: ``False`` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under ``mine_functions`` in the
minion/master config or pillar.
CLI Example:
.. code-block:: bash
salt-run mine.update '*'
salt-run mine.update 'juniper-edges' tgt_type='nodegroup'
'''
ret = __salt__['salt.execute'](tgt,
'mine.update',
tgt_type=tgt_type,
clear=clear,
mine_functions=mine_functions)
return ret
|
.. versionadded:: 2017.7.0
Update the mine data on a certain group of minions.
tgt
Which minions to target for the execution.
tgt_type: ``glob``
The type of ``tgt``.
clear: ``False``
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: ``False`` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under ``mine_functions`` in the
minion/master config or pillar.
CLI Example:
.. code-block:: bash
salt-run mine.update '*'
salt-run mine.update 'juniper-edges' tgt_type='nodegroup'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/mine.py#L31-L69
| null |
# -*- coding: utf-8 -*-
'''
A runner to access data from the salt mine
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import logging
# Import salt libs
import salt.utils.minions
log = logging.getLevelName(__name__)
def get(tgt, fun, tgt_type='glob'):
'''
Gathers the data from the specified minions' mine, pass in the target,
function to look up and the target type
CLI Example:
.. code-block:: bash
salt-run mine.get '*' network.interfaces
'''
ret = salt.utils.minions.mine_get(tgt, fun, tgt_type, __opts__)
return ret
|
saltstack/salt
|
salt/utils/nxos.py
|
nxapi_request
|
python
|
def nxapi_request(commands,
method='cli_show',
**kwargs):
'''
Send exec and config commands to the NX-OS device over NX-API.
commands
The exec or config commands to be sent.
method:
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_show``.
transport: ``https``
Specifies the type of connection transport to use. Valid values for the
connection are ``http``, and ``https``.
host: ``localhost``
The IP address or DNS host name of the device.
username: ``admin``
The username to pass to the device to authenticate the NX-API connection.
password
The password to pass to the device to authenticate the NX-API connection.
port
The TCP port of the endpoint for the NX-API connection. If this keyword is
not specified, the default value is automatically determined by the
transport type (``80`` for ``http``, or ``443`` for ``https``).
timeout: ``60``
Time in seconds to wait for the device to respond. Default: 60 seconds.
verify: ``True``
Either a boolean, in which case it controls whether we verify the NX-API
TLS certificate, or a string, in which case it must be a path to a CA bundle
to use. Defaults to ``True``.
'''
client = NxapiClient(**kwargs)
return client.request(method, commands)
|
Send exec and config commands to the NX-OS device over NX-API.
commands
The exec or config commands to be sent.
method:
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_show``.
transport: ``https``
Specifies the type of connection transport to use. Valid values for the
connection are ``http``, and ``https``.
host: ``localhost``
The IP address or DNS host name of the device.
username: ``admin``
The username to pass to the device to authenticate the NX-API connection.
password
The password to pass to the device to authenticate the NX-API connection.
port
The TCP port of the endpoint for the NX-API connection. If this keyword is
not specified, the default value is automatically determined by the
transport type (``80`` for ``http``, or ``443`` for ``https``).
timeout: ``60``
Time in seconds to wait for the device to respond. Default: 60 seconds.
verify: ``True``
Either a boolean, in which case it controls whether we verify the NX-API
TLS certificate, or a string, in which case it must be a path to a CA bundle
to use. Defaults to ``True``.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L271-L313
|
[
"def request(self, type, command_list):\n '''\n Send NX-API JSON request to the NX-OS device.\n '''\n req = self._build_request(type, command_list)\n if self.nxargs['connect_over_uds']:\n self.connection.request('POST', req['url'], req['payload'], req['headers'])\n response = self.connection.getresponse()\n else:\n response = self.connection(req['url'],\n method='POST',\n opts=req['opts'],\n data=req['payload'],\n header_dict=req['headers'],\n decode=True,\n decode_type='json',\n **self.nxargs)\n\n return self.parse_response(response, command_list)\n"
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Cisco and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Util functions for the NXOS modules.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python std lib
import json
import logging
import os
import socket
import re
import collections
from salt.ext.six import string_types
from salt.exceptions import (NxosClientError, NxosError,
NxosRequestNotSupported, CommandExecutionError)
# Import salt libs
import salt.utils.http
from salt.ext.six.moves import zip
try:
from salt.utils.args import clean_kwargs
except ImportError:
from salt.utils import clean_kwargs
# Disable pylint check since httplib is not available in python3
try:
import httplib # pylint: disable=W1699
except ImportError:
import http.client
httplib = http.client
log = logging.getLogger(__name__)
class UHTTPConnection(httplib.HTTPConnection): # pylint: disable=W1699
'''
Subclass of Python library HTTPConnection that uses a unix-domain socket.
'''
def __init__(self, path):
httplib.HTTPConnection.__init__(self, 'localhost')
self.path = path
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self.path)
self.sock = sock
class NxapiClient(object):
'''
Class representing an NX-API client that connects over http(s) or
unix domain socket (UDS).
'''
# Location of unix domain socket for NX-API localhost
NXAPI_UDS = '/tmp/nginx_local/nginx_1_be_nxapi.sock'
# NXAPI listens for remote connections to "http(s)://<switch IP>/ins"
# NXAPI listens for local connections to "http(s)://<UDS>/ins_local"
NXAPI_REMOTE_URI_PATH = '/ins'
NXAPI_UDS_URI_PATH = '/ins_local'
NXAPI_VERSION = '1.0'
def __init__(self, **nxos_kwargs):
'''
Initialize NxapiClient() connection object. By default this connects
to the local unix domain socket (UDS). If http(s) is required to
connect to a remote device then
nxos_kwargs['host'],
nxos_kwargs['username'],
nxos_kwargs['password'],
nxos_kwargs['transport'],
nxos_kwargs['port'],
parameters must be provided.
'''
self.nxargs = self._prepare_conn_args(clean_kwargs(**nxos_kwargs))
# Default: Connect to unix domain socket on localhost.
if self.nxargs['connect_over_uds']:
if not os.path.exists(self.NXAPI_UDS):
raise NxosClientError("No host specified and no UDS found at {0}\n".format(self.NXAPI_UDS))
# Create UHTTPConnection object for NX-API communication over UDS.
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over unix domain socket')
self.connection = UHTTPConnection(self.NXAPI_UDS)
else:
# Remote connection - Proxy Minion, connect over http(s)
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over %s', self.nxargs['transport'])
self.connection = salt.utils.http.query
def _use_remote_connection(self, kwargs):
'''
Determine if connection is local or remote
'''
kwargs['host'] = kwargs.get('host')
kwargs['username'] = kwargs.get('username')
kwargs['password'] = kwargs.get('password')
if kwargs['host'] is None or \
kwargs['username'] is None or \
kwargs['password'] is None:
return False
else:
return True
def _prepare_conn_args(self, kwargs):
'''
Set connection arguments for remote or local connection.
'''
kwargs['connect_over_uds'] = True
kwargs['timeout'] = kwargs.get('timeout', 60)
kwargs['cookie'] = kwargs.get('cookie', 'admin')
if self._use_remote_connection(kwargs):
kwargs['transport'] = kwargs.get('transport', 'https')
if kwargs['transport'] == 'https':
kwargs['port'] = kwargs.get('port', 443)
else:
kwargs['port'] = kwargs.get('port', 80)
kwargs['verify'] = kwargs.get('verify', True)
if isinstance(kwargs['verify'], bool):
kwargs['verify_ssl'] = kwargs['verify']
else:
kwargs['ca_bundle'] = kwargs['verify']
kwargs['connect_over_uds'] = False
return kwargs
def _build_request(self, type, commands):
'''
Build NX-API JSON request.
'''
request = {}
headers = {
'content-type': 'application/json',
}
if self.nxargs['connect_over_uds']:
user = self.nxargs['cookie']
headers['cookie'] = 'nxapi_auth=' + user + ':local'
request['url'] = self.NXAPI_UDS_URI_PATH
else:
request['url'] = '{transport}://{host}:{port}{uri}'.format(
transport=self.nxargs['transport'],
host=self.nxargs['host'],
port=self.nxargs['port'],
uri=self.NXAPI_REMOTE_URI_PATH,
)
if isinstance(commands, (list, set, tuple)):
commands = ' ; '.join(commands)
payload = {}
payload['ins_api'] = {
'version': self.NXAPI_VERSION,
'type': type,
'chunk': '0',
'sid': '1',
'input': commands,
'output_format': 'json',
}
request['headers'] = headers
request['payload'] = json.dumps(payload)
request['opts'] = {
'http_request_timeout': self.nxargs['timeout']
}
log.info('request: %s', request)
return request
def request(self, type, command_list):
'''
Send NX-API JSON request to the NX-OS device.
'''
req = self._build_request(type, command_list)
if self.nxargs['connect_over_uds']:
self.connection.request('POST', req['url'], req['payload'], req['headers'])
response = self.connection.getresponse()
else:
response = self.connection(req['url'],
method='POST',
opts=req['opts'],
data=req['payload'],
header_dict=req['headers'],
decode=True,
decode_type='json',
**self.nxargs)
return self.parse_response(response, command_list)
def parse_response(self, response, command_list):
'''
Parse NX-API JSON response from the NX-OS device.
'''
# Check for 500 level NX-API Server Errors
if isinstance(response, collections.Iterable) and 'status' in response:
if int(response['status']) >= 500:
raise NxosError('{}'.format(response))
else:
raise NxosError('NX-API Request Not Supported: {}'.format(response))
if isinstance(response, collections.Iterable):
body = response['dict']
else:
body = response
if self.nxargs['connect_over_uds']:
body = json.loads(response.read().decode('utf-8'))
# Proceed with caution. The JSON may not be complete.
# Don't just return body['ins_api']['outputs']['output'] directly.
output = body.get('ins_api')
if output is None:
raise NxosClientError('Unexpected JSON output\n{0}'.format(body))
if output.get('outputs'):
output = output['outputs']
if output.get('output'):
output = output['output']
# The result list stores results for each command that was sent to
# nxapi.
result = []
# Keep track of successful commands using previous_commands list so
# they can be displayed if a specific command fails in a chain of
# commands.
previous_commands = []
# Make sure output and command_list lists to be processed in the
# subesequent loop.
if not isinstance(output, list):
output = [output]
if isinstance(command_list, string_types):
command_list = [cmd.strip() for cmd in command_list.split(';')]
if not isinstance(command_list, list):
command_list = [command_list]
for cmd_result, cmd in zip(output, command_list):
code = cmd_result.get('code')
msg = cmd_result.get('msg')
log.info('command %s:', cmd)
log.info('PARSE_RESPONSE: %s %s', code, msg)
if code == '400':
raise CommandExecutionError({
'rejected_input': cmd,
'code': code,
'message': msg,
'cli_error': cmd_result.get('clierror'),
'previous_commands': previous_commands,
})
elif code == '413':
raise NxosRequestNotSupported('Error 413: {}'.format(msg))
elif code != '200':
raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))
else:
previous_commands.append(cmd)
result.append(cmd_result['body'])
return result
def ping(**kwargs):
'''
Verify connection to the NX-OS device over UDS.
'''
return NxapiClient(**kwargs).nxargs['connect_over_uds']
# Grains Functions
def _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
'''
Internal helper function to parse sotware grain information.
'''
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
'''
Internal helper function to parse hardware grain information.
'''
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
'''
Internal helper function to parse plugin grain information.
'''
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def version_info():
client = NxapiClient()
return client.request('cli_show_ascii', 'show version')[0]
def system_info(data):
'''
Helper method to return parsed system_info
from the 'show version' command.
'''
if not data:
return {}
info = {
'software': _parse_software(data),
'hardware': _parse_hardware(data),
'plugins': _parse_plugins(data),
}
return {'nxos': info}
|
saltstack/salt
|
salt/utils/nxos.py
|
system_info
|
python
|
def system_info(data):
'''
Helper method to return parsed system_info
from the 'show version' command.
'''
if not data:
return {}
info = {
'software': _parse_software(data),
'hardware': _parse_hardware(data),
'plugins': _parse_plugins(data),
}
return {'nxos': info}
|
Helper method to return parsed system_info
from the 'show version' command.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L372-L384
|
[
"def _parse_software(data):\n '''\n Internal helper function to parse sotware grain information.\n '''\n ret = {'software': {}}\n software = _parser('Software').search(data).group(0)\n matcher = re.compile('^ ([^:]+): *([^\\n]+)', re.MULTILINE)\n for line in matcher.finditer(software):\n key, val = line.groups()\n ret['software'][key] = val\n return ret['software']\n",
"def _parse_hardware(data):\n '''\n Internal helper function to parse hardware grain information.\n '''\n ret = {'hardware': {}}\n hardware = _parser('Hardware').search(data).group(0)\n matcher = re.compile('^ ([^:\\n]+): *([^\\n]+)', re.MULTILINE)\n for line in matcher.finditer(hardware):\n key, val = line.groups()\n ret['hardware'][key] = val\n return ret['hardware']\n",
"def _parse_plugins(data):\n '''\n Internal helper function to parse plugin grain information.\n '''\n ret = {'plugins': []}\n plugins = _parser('plugin').search(data).group(0)\n matcher = re.compile('^ (?:([^,]+), )+([^\\n]+)', re.MULTILINE)\n for line in matcher.finditer(plugins):\n ret['plugins'].extend(line.groups())\n return ret['plugins']\n"
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Cisco and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Util functions for the NXOS modules.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python std lib
import json
import logging
import os
import socket
import re
import collections
from salt.ext.six import string_types
from salt.exceptions import (NxosClientError, NxosError,
NxosRequestNotSupported, CommandExecutionError)
# Import salt libs
import salt.utils.http
from salt.ext.six.moves import zip
try:
from salt.utils.args import clean_kwargs
except ImportError:
from salt.utils import clean_kwargs
# Disable pylint check since httplib is not available in python3
try:
import httplib # pylint: disable=W1699
except ImportError:
import http.client
httplib = http.client
log = logging.getLogger(__name__)
class UHTTPConnection(httplib.HTTPConnection): # pylint: disable=W1699
'''
Subclass of Python library HTTPConnection that uses a unix-domain socket.
'''
def __init__(self, path):
httplib.HTTPConnection.__init__(self, 'localhost')
self.path = path
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self.path)
self.sock = sock
class NxapiClient(object):
'''
Class representing an NX-API client that connects over http(s) or
unix domain socket (UDS).
'''
# Location of unix domain socket for NX-API localhost
NXAPI_UDS = '/tmp/nginx_local/nginx_1_be_nxapi.sock'
# NXAPI listens for remote connections to "http(s)://<switch IP>/ins"
# NXAPI listens for local connections to "http(s)://<UDS>/ins_local"
NXAPI_REMOTE_URI_PATH = '/ins'
NXAPI_UDS_URI_PATH = '/ins_local'
NXAPI_VERSION = '1.0'
def __init__(self, **nxos_kwargs):
'''
Initialize NxapiClient() connection object. By default this connects
to the local unix domain socket (UDS). If http(s) is required to
connect to a remote device then
nxos_kwargs['host'],
nxos_kwargs['username'],
nxos_kwargs['password'],
nxos_kwargs['transport'],
nxos_kwargs['port'],
parameters must be provided.
'''
self.nxargs = self._prepare_conn_args(clean_kwargs(**nxos_kwargs))
# Default: Connect to unix domain socket on localhost.
if self.nxargs['connect_over_uds']:
if not os.path.exists(self.NXAPI_UDS):
raise NxosClientError("No host specified and no UDS found at {0}\n".format(self.NXAPI_UDS))
# Create UHTTPConnection object for NX-API communication over UDS.
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over unix domain socket')
self.connection = UHTTPConnection(self.NXAPI_UDS)
else:
# Remote connection - Proxy Minion, connect over http(s)
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over %s', self.nxargs['transport'])
self.connection = salt.utils.http.query
def _use_remote_connection(self, kwargs):
'''
Determine if connection is local or remote
'''
kwargs['host'] = kwargs.get('host')
kwargs['username'] = kwargs.get('username')
kwargs['password'] = kwargs.get('password')
if kwargs['host'] is None or \
kwargs['username'] is None or \
kwargs['password'] is None:
return False
else:
return True
def _prepare_conn_args(self, kwargs):
'''
Set connection arguments for remote or local connection.
'''
kwargs['connect_over_uds'] = True
kwargs['timeout'] = kwargs.get('timeout', 60)
kwargs['cookie'] = kwargs.get('cookie', 'admin')
if self._use_remote_connection(kwargs):
kwargs['transport'] = kwargs.get('transport', 'https')
if kwargs['transport'] == 'https':
kwargs['port'] = kwargs.get('port', 443)
else:
kwargs['port'] = kwargs.get('port', 80)
kwargs['verify'] = kwargs.get('verify', True)
if isinstance(kwargs['verify'], bool):
kwargs['verify_ssl'] = kwargs['verify']
else:
kwargs['ca_bundle'] = kwargs['verify']
kwargs['connect_over_uds'] = False
return kwargs
def _build_request(self, type, commands):
'''
Build NX-API JSON request.
'''
request = {}
headers = {
'content-type': 'application/json',
}
if self.nxargs['connect_over_uds']:
user = self.nxargs['cookie']
headers['cookie'] = 'nxapi_auth=' + user + ':local'
request['url'] = self.NXAPI_UDS_URI_PATH
else:
request['url'] = '{transport}://{host}:{port}{uri}'.format(
transport=self.nxargs['transport'],
host=self.nxargs['host'],
port=self.nxargs['port'],
uri=self.NXAPI_REMOTE_URI_PATH,
)
if isinstance(commands, (list, set, tuple)):
commands = ' ; '.join(commands)
payload = {}
payload['ins_api'] = {
'version': self.NXAPI_VERSION,
'type': type,
'chunk': '0',
'sid': '1',
'input': commands,
'output_format': 'json',
}
request['headers'] = headers
request['payload'] = json.dumps(payload)
request['opts'] = {
'http_request_timeout': self.nxargs['timeout']
}
log.info('request: %s', request)
return request
def request(self, type, command_list):
'''
Send NX-API JSON request to the NX-OS device.
'''
req = self._build_request(type, command_list)
if self.nxargs['connect_over_uds']:
self.connection.request('POST', req['url'], req['payload'], req['headers'])
response = self.connection.getresponse()
else:
response = self.connection(req['url'],
method='POST',
opts=req['opts'],
data=req['payload'],
header_dict=req['headers'],
decode=True,
decode_type='json',
**self.nxargs)
return self.parse_response(response, command_list)
def parse_response(self, response, command_list):
'''
Parse NX-API JSON response from the NX-OS device.
'''
# Check for 500 level NX-API Server Errors
if isinstance(response, collections.Iterable) and 'status' in response:
if int(response['status']) >= 500:
raise NxosError('{}'.format(response))
else:
raise NxosError('NX-API Request Not Supported: {}'.format(response))
if isinstance(response, collections.Iterable):
body = response['dict']
else:
body = response
if self.nxargs['connect_over_uds']:
body = json.loads(response.read().decode('utf-8'))
# Proceed with caution. The JSON may not be complete.
# Don't just return body['ins_api']['outputs']['output'] directly.
output = body.get('ins_api')
if output is None:
raise NxosClientError('Unexpected JSON output\n{0}'.format(body))
if output.get('outputs'):
output = output['outputs']
if output.get('output'):
output = output['output']
# The result list stores results for each command that was sent to
# nxapi.
result = []
# Keep track of successful commands using previous_commands list so
# they can be displayed if a specific command fails in a chain of
# commands.
previous_commands = []
# Make sure output and command_list lists to be processed in the
# subesequent loop.
if not isinstance(output, list):
output = [output]
if isinstance(command_list, string_types):
command_list = [cmd.strip() for cmd in command_list.split(';')]
if not isinstance(command_list, list):
command_list = [command_list]
for cmd_result, cmd in zip(output, command_list):
code = cmd_result.get('code')
msg = cmd_result.get('msg')
log.info('command %s:', cmd)
log.info('PARSE_RESPONSE: %s %s', code, msg)
if code == '400':
raise CommandExecutionError({
'rejected_input': cmd,
'code': code,
'message': msg,
'cli_error': cmd_result.get('clierror'),
'previous_commands': previous_commands,
})
elif code == '413':
raise NxosRequestNotSupported('Error 413: {}'.format(msg))
elif code != '200':
raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))
else:
previous_commands.append(cmd)
result.append(cmd_result['body'])
return result
def nxapi_request(commands,
method='cli_show',
**kwargs):
'''
Send exec and config commands to the NX-OS device over NX-API.
commands
The exec or config commands to be sent.
method:
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_show``.
transport: ``https``
Specifies the type of connection transport to use. Valid values for the
connection are ``http``, and ``https``.
host: ``localhost``
The IP address or DNS host name of the device.
username: ``admin``
The username to pass to the device to authenticate the NX-API connection.
password
The password to pass to the device to authenticate the NX-API connection.
port
The TCP port of the endpoint for the NX-API connection. If this keyword is
not specified, the default value is automatically determined by the
transport type (``80`` for ``http``, or ``443`` for ``https``).
timeout: ``60``
Time in seconds to wait for the device to respond. Default: 60 seconds.
verify: ``True``
Either a boolean, in which case it controls whether we verify the NX-API
TLS certificate, or a string, in which case it must be a path to a CA bundle
to use. Defaults to ``True``.
'''
client = NxapiClient(**kwargs)
return client.request(method, commands)
def ping(**kwargs):
'''
Verify connection to the NX-OS device over UDS.
'''
return NxapiClient(**kwargs).nxargs['connect_over_uds']
# Grains Functions
def _parser(block):
return re.compile('^{block}\n(?:^[ \n].*$\n?)+'.format(block=block), re.MULTILINE)
def _parse_software(data):
'''
Internal helper function to parse sotware grain information.
'''
ret = {'software': {}}
software = _parser('Software').search(data).group(0)
matcher = re.compile('^ ([^:]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(software):
key, val = line.groups()
ret['software'][key] = val
return ret['software']
def _parse_hardware(data):
'''
Internal helper function to parse hardware grain information.
'''
ret = {'hardware': {}}
hardware = _parser('Hardware').search(data).group(0)
matcher = re.compile('^ ([^:\n]+): *([^\n]+)', re.MULTILINE)
for line in matcher.finditer(hardware):
key, val = line.groups()
ret['hardware'][key] = val
return ret['hardware']
def _parse_plugins(data):
'''
Internal helper function to parse plugin grain information.
'''
ret = {'plugins': []}
plugins = _parser('plugin').search(data).group(0)
matcher = re.compile('^ (?:([^,]+), )+([^\n]+)', re.MULTILINE)
for line in matcher.finditer(plugins):
ret['plugins'].extend(line.groups())
return ret['plugins']
def version_info():
client = NxapiClient()
return client.request('cli_show_ascii', 'show version')[0]
|
saltstack/salt
|
salt/utils/nxos.py
|
NxapiClient._use_remote_connection
|
python
|
def _use_remote_connection(self, kwargs):
'''
Determine if connection is local or remote
'''
kwargs['host'] = kwargs.get('host')
kwargs['username'] = kwargs.get('username')
kwargs['password'] = kwargs.get('password')
if kwargs['host'] is None or \
kwargs['username'] is None or \
kwargs['password'] is None:
return False
else:
return True
|
Determine if connection is local or remote
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L107-L119
| null |
class NxapiClient(object):
'''
Class representing an NX-API client that connects over http(s) or
unix domain socket (UDS).
'''
# Location of unix domain socket for NX-API localhost
NXAPI_UDS = '/tmp/nginx_local/nginx_1_be_nxapi.sock'
# NXAPI listens for remote connections to "http(s)://<switch IP>/ins"
# NXAPI listens for local connections to "http(s)://<UDS>/ins_local"
NXAPI_REMOTE_URI_PATH = '/ins'
NXAPI_UDS_URI_PATH = '/ins_local'
NXAPI_VERSION = '1.0'
def __init__(self, **nxos_kwargs):
'''
Initialize NxapiClient() connection object. By default this connects
to the local unix domain socket (UDS). If http(s) is required to
connect to a remote device then
nxos_kwargs['host'],
nxos_kwargs['username'],
nxos_kwargs['password'],
nxos_kwargs['transport'],
nxos_kwargs['port'],
parameters must be provided.
'''
self.nxargs = self._prepare_conn_args(clean_kwargs(**nxos_kwargs))
# Default: Connect to unix domain socket on localhost.
if self.nxargs['connect_over_uds']:
if not os.path.exists(self.NXAPI_UDS):
raise NxosClientError("No host specified and no UDS found at {0}\n".format(self.NXAPI_UDS))
# Create UHTTPConnection object for NX-API communication over UDS.
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over unix domain socket')
self.connection = UHTTPConnection(self.NXAPI_UDS)
else:
# Remote connection - Proxy Minion, connect over http(s)
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over %s', self.nxargs['transport'])
self.connection = salt.utils.http.query
def _prepare_conn_args(self, kwargs):
'''
Set connection arguments for remote or local connection.
'''
kwargs['connect_over_uds'] = True
kwargs['timeout'] = kwargs.get('timeout', 60)
kwargs['cookie'] = kwargs.get('cookie', 'admin')
if self._use_remote_connection(kwargs):
kwargs['transport'] = kwargs.get('transport', 'https')
if kwargs['transport'] == 'https':
kwargs['port'] = kwargs.get('port', 443)
else:
kwargs['port'] = kwargs.get('port', 80)
kwargs['verify'] = kwargs.get('verify', True)
if isinstance(kwargs['verify'], bool):
kwargs['verify_ssl'] = kwargs['verify']
else:
kwargs['ca_bundle'] = kwargs['verify']
kwargs['connect_over_uds'] = False
return kwargs
def _build_request(self, type, commands):
'''
Build NX-API JSON request.
'''
request = {}
headers = {
'content-type': 'application/json',
}
if self.nxargs['connect_over_uds']:
user = self.nxargs['cookie']
headers['cookie'] = 'nxapi_auth=' + user + ':local'
request['url'] = self.NXAPI_UDS_URI_PATH
else:
request['url'] = '{transport}://{host}:{port}{uri}'.format(
transport=self.nxargs['transport'],
host=self.nxargs['host'],
port=self.nxargs['port'],
uri=self.NXAPI_REMOTE_URI_PATH,
)
if isinstance(commands, (list, set, tuple)):
commands = ' ; '.join(commands)
payload = {}
payload['ins_api'] = {
'version': self.NXAPI_VERSION,
'type': type,
'chunk': '0',
'sid': '1',
'input': commands,
'output_format': 'json',
}
request['headers'] = headers
request['payload'] = json.dumps(payload)
request['opts'] = {
'http_request_timeout': self.nxargs['timeout']
}
log.info('request: %s', request)
return request
def request(self, type, command_list):
'''
Send NX-API JSON request to the NX-OS device.
'''
req = self._build_request(type, command_list)
if self.nxargs['connect_over_uds']:
self.connection.request('POST', req['url'], req['payload'], req['headers'])
response = self.connection.getresponse()
else:
response = self.connection(req['url'],
method='POST',
opts=req['opts'],
data=req['payload'],
header_dict=req['headers'],
decode=True,
decode_type='json',
**self.nxargs)
return self.parse_response(response, command_list)
def parse_response(self, response, command_list):
'''
Parse NX-API JSON response from the NX-OS device.
'''
# Check for 500 level NX-API Server Errors
if isinstance(response, collections.Iterable) and 'status' in response:
if int(response['status']) >= 500:
raise NxosError('{}'.format(response))
else:
raise NxosError('NX-API Request Not Supported: {}'.format(response))
if isinstance(response, collections.Iterable):
body = response['dict']
else:
body = response
if self.nxargs['connect_over_uds']:
body = json.loads(response.read().decode('utf-8'))
# Proceed with caution. The JSON may not be complete.
# Don't just return body['ins_api']['outputs']['output'] directly.
output = body.get('ins_api')
if output is None:
raise NxosClientError('Unexpected JSON output\n{0}'.format(body))
if output.get('outputs'):
output = output['outputs']
if output.get('output'):
output = output['output']
# The result list stores results for each command that was sent to
# nxapi.
result = []
# Keep track of successful commands using previous_commands list so
# they can be displayed if a specific command fails in a chain of
# commands.
previous_commands = []
# Make sure output and command_list lists to be processed in the
# subesequent loop.
if not isinstance(output, list):
output = [output]
if isinstance(command_list, string_types):
command_list = [cmd.strip() for cmd in command_list.split(';')]
if not isinstance(command_list, list):
command_list = [command_list]
for cmd_result, cmd in zip(output, command_list):
code = cmd_result.get('code')
msg = cmd_result.get('msg')
log.info('command %s:', cmd)
log.info('PARSE_RESPONSE: %s %s', code, msg)
if code == '400':
raise CommandExecutionError({
'rejected_input': cmd,
'code': code,
'message': msg,
'cli_error': cmd_result.get('clierror'),
'previous_commands': previous_commands,
})
elif code == '413':
raise NxosRequestNotSupported('Error 413: {}'.format(msg))
elif code != '200':
raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))
else:
previous_commands.append(cmd)
result.append(cmd_result['body'])
return result
|
saltstack/salt
|
salt/utils/nxos.py
|
NxapiClient._prepare_conn_args
|
python
|
def _prepare_conn_args(self, kwargs):
'''
Set connection arguments for remote or local connection.
'''
kwargs['connect_over_uds'] = True
kwargs['timeout'] = kwargs.get('timeout', 60)
kwargs['cookie'] = kwargs.get('cookie', 'admin')
if self._use_remote_connection(kwargs):
kwargs['transport'] = kwargs.get('transport', 'https')
if kwargs['transport'] == 'https':
kwargs['port'] = kwargs.get('port', 443)
else:
kwargs['port'] = kwargs.get('port', 80)
kwargs['verify'] = kwargs.get('verify', True)
if isinstance(kwargs['verify'], bool):
kwargs['verify_ssl'] = kwargs['verify']
else:
kwargs['ca_bundle'] = kwargs['verify']
kwargs['connect_over_uds'] = False
return kwargs
|
Set connection arguments for remote or local connection.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L121-L140
|
[
"def _use_remote_connection(self, kwargs):\n '''\n Determine if connection is local or remote\n '''\n kwargs['host'] = kwargs.get('host')\n kwargs['username'] = kwargs.get('username')\n kwargs['password'] = kwargs.get('password')\n if kwargs['host'] is None or \\\n kwargs['username'] is None or \\\n kwargs['password'] is None:\n return False\n else:\n return True\n"
] |
class NxapiClient(object):
'''
Class representing an NX-API client that connects over http(s) or
unix domain socket (UDS).
'''
# Location of unix domain socket for NX-API localhost
NXAPI_UDS = '/tmp/nginx_local/nginx_1_be_nxapi.sock'
# NXAPI listens for remote connections to "http(s)://<switch IP>/ins"
# NXAPI listens for local connections to "http(s)://<UDS>/ins_local"
NXAPI_REMOTE_URI_PATH = '/ins'
NXAPI_UDS_URI_PATH = '/ins_local'
NXAPI_VERSION = '1.0'
def __init__(self, **nxos_kwargs):
'''
Initialize NxapiClient() connection object. By default this connects
to the local unix domain socket (UDS). If http(s) is required to
connect to a remote device then
nxos_kwargs['host'],
nxos_kwargs['username'],
nxos_kwargs['password'],
nxos_kwargs['transport'],
nxos_kwargs['port'],
parameters must be provided.
'''
self.nxargs = self._prepare_conn_args(clean_kwargs(**nxos_kwargs))
# Default: Connect to unix domain socket on localhost.
if self.nxargs['connect_over_uds']:
if not os.path.exists(self.NXAPI_UDS):
raise NxosClientError("No host specified and no UDS found at {0}\n".format(self.NXAPI_UDS))
# Create UHTTPConnection object for NX-API communication over UDS.
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over unix domain socket')
self.connection = UHTTPConnection(self.NXAPI_UDS)
else:
# Remote connection - Proxy Minion, connect over http(s)
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over %s', self.nxargs['transport'])
self.connection = salt.utils.http.query
def _use_remote_connection(self, kwargs):
'''
Determine if connection is local or remote
'''
kwargs['host'] = kwargs.get('host')
kwargs['username'] = kwargs.get('username')
kwargs['password'] = kwargs.get('password')
if kwargs['host'] is None or \
kwargs['username'] is None or \
kwargs['password'] is None:
return False
else:
return True
def _build_request(self, type, commands):
'''
Build NX-API JSON request.
'''
request = {}
headers = {
'content-type': 'application/json',
}
if self.nxargs['connect_over_uds']:
user = self.nxargs['cookie']
headers['cookie'] = 'nxapi_auth=' + user + ':local'
request['url'] = self.NXAPI_UDS_URI_PATH
else:
request['url'] = '{transport}://{host}:{port}{uri}'.format(
transport=self.nxargs['transport'],
host=self.nxargs['host'],
port=self.nxargs['port'],
uri=self.NXAPI_REMOTE_URI_PATH,
)
if isinstance(commands, (list, set, tuple)):
commands = ' ; '.join(commands)
payload = {}
payload['ins_api'] = {
'version': self.NXAPI_VERSION,
'type': type,
'chunk': '0',
'sid': '1',
'input': commands,
'output_format': 'json',
}
request['headers'] = headers
request['payload'] = json.dumps(payload)
request['opts'] = {
'http_request_timeout': self.nxargs['timeout']
}
log.info('request: %s', request)
return request
def request(self, type, command_list):
'''
Send NX-API JSON request to the NX-OS device.
'''
req = self._build_request(type, command_list)
if self.nxargs['connect_over_uds']:
self.connection.request('POST', req['url'], req['payload'], req['headers'])
response = self.connection.getresponse()
else:
response = self.connection(req['url'],
method='POST',
opts=req['opts'],
data=req['payload'],
header_dict=req['headers'],
decode=True,
decode_type='json',
**self.nxargs)
return self.parse_response(response, command_list)
def parse_response(self, response, command_list):
'''
Parse NX-API JSON response from the NX-OS device.
'''
# Check for 500 level NX-API Server Errors
if isinstance(response, collections.Iterable) and 'status' in response:
if int(response['status']) >= 500:
raise NxosError('{}'.format(response))
else:
raise NxosError('NX-API Request Not Supported: {}'.format(response))
if isinstance(response, collections.Iterable):
body = response['dict']
else:
body = response
if self.nxargs['connect_over_uds']:
body = json.loads(response.read().decode('utf-8'))
# Proceed with caution. The JSON may not be complete.
# Don't just return body['ins_api']['outputs']['output'] directly.
output = body.get('ins_api')
if output is None:
raise NxosClientError('Unexpected JSON output\n{0}'.format(body))
if output.get('outputs'):
output = output['outputs']
if output.get('output'):
output = output['output']
# The result list stores results for each command that was sent to
# nxapi.
result = []
# Keep track of successful commands using previous_commands list so
# they can be displayed if a specific command fails in a chain of
# commands.
previous_commands = []
# Make sure output and command_list lists to be processed in the
# subesequent loop.
if not isinstance(output, list):
output = [output]
if isinstance(command_list, string_types):
command_list = [cmd.strip() for cmd in command_list.split(';')]
if not isinstance(command_list, list):
command_list = [command_list]
for cmd_result, cmd in zip(output, command_list):
code = cmd_result.get('code')
msg = cmd_result.get('msg')
log.info('command %s:', cmd)
log.info('PARSE_RESPONSE: %s %s', code, msg)
if code == '400':
raise CommandExecutionError({
'rejected_input': cmd,
'code': code,
'message': msg,
'cli_error': cmd_result.get('clierror'),
'previous_commands': previous_commands,
})
elif code == '413':
raise NxosRequestNotSupported('Error 413: {}'.format(msg))
elif code != '200':
raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))
else:
previous_commands.append(cmd)
result.append(cmd_result['body'])
return result
|
saltstack/salt
|
salt/utils/nxos.py
|
NxapiClient._build_request
|
python
|
def _build_request(self, type, commands):
'''
Build NX-API JSON request.
'''
request = {}
headers = {
'content-type': 'application/json',
}
if self.nxargs['connect_over_uds']:
user = self.nxargs['cookie']
headers['cookie'] = 'nxapi_auth=' + user + ':local'
request['url'] = self.NXAPI_UDS_URI_PATH
else:
request['url'] = '{transport}://{host}:{port}{uri}'.format(
transport=self.nxargs['transport'],
host=self.nxargs['host'],
port=self.nxargs['port'],
uri=self.NXAPI_REMOTE_URI_PATH,
)
if isinstance(commands, (list, set, tuple)):
commands = ' ; '.join(commands)
payload = {}
payload['ins_api'] = {
'version': self.NXAPI_VERSION,
'type': type,
'chunk': '0',
'sid': '1',
'input': commands,
'output_format': 'json',
}
request['headers'] = headers
request['payload'] = json.dumps(payload)
request['opts'] = {
'http_request_timeout': self.nxargs['timeout']
}
log.info('request: %s', request)
return request
|
Build NX-API JSON request.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L142-L179
| null |
class NxapiClient(object):
'''
Class representing an NX-API client that connects over http(s) or
unix domain socket (UDS).
'''
# Location of unix domain socket for NX-API localhost
NXAPI_UDS = '/tmp/nginx_local/nginx_1_be_nxapi.sock'
# NXAPI listens for remote connections to "http(s)://<switch IP>/ins"
# NXAPI listens for local connections to "http(s)://<UDS>/ins_local"
NXAPI_REMOTE_URI_PATH = '/ins'
NXAPI_UDS_URI_PATH = '/ins_local'
NXAPI_VERSION = '1.0'
def __init__(self, **nxos_kwargs):
'''
Initialize NxapiClient() connection object. By default this connects
to the local unix domain socket (UDS). If http(s) is required to
connect to a remote device then
nxos_kwargs['host'],
nxos_kwargs['username'],
nxos_kwargs['password'],
nxos_kwargs['transport'],
nxos_kwargs['port'],
parameters must be provided.
'''
self.nxargs = self._prepare_conn_args(clean_kwargs(**nxos_kwargs))
# Default: Connect to unix domain socket on localhost.
if self.nxargs['connect_over_uds']:
if not os.path.exists(self.NXAPI_UDS):
raise NxosClientError("No host specified and no UDS found at {0}\n".format(self.NXAPI_UDS))
# Create UHTTPConnection object for NX-API communication over UDS.
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over unix domain socket')
self.connection = UHTTPConnection(self.NXAPI_UDS)
else:
# Remote connection - Proxy Minion, connect over http(s)
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over %s', self.nxargs['transport'])
self.connection = salt.utils.http.query
def _use_remote_connection(self, kwargs):
'''
Determine if connection is local or remote
'''
kwargs['host'] = kwargs.get('host')
kwargs['username'] = kwargs.get('username')
kwargs['password'] = kwargs.get('password')
if kwargs['host'] is None or \
kwargs['username'] is None or \
kwargs['password'] is None:
return False
else:
return True
def _prepare_conn_args(self, kwargs):
'''
Set connection arguments for remote or local connection.
'''
kwargs['connect_over_uds'] = True
kwargs['timeout'] = kwargs.get('timeout', 60)
kwargs['cookie'] = kwargs.get('cookie', 'admin')
if self._use_remote_connection(kwargs):
kwargs['transport'] = kwargs.get('transport', 'https')
if kwargs['transport'] == 'https':
kwargs['port'] = kwargs.get('port', 443)
else:
kwargs['port'] = kwargs.get('port', 80)
kwargs['verify'] = kwargs.get('verify', True)
if isinstance(kwargs['verify'], bool):
kwargs['verify_ssl'] = kwargs['verify']
else:
kwargs['ca_bundle'] = kwargs['verify']
kwargs['connect_over_uds'] = False
return kwargs
def request(self, type, command_list):
'''
Send NX-API JSON request to the NX-OS device.
'''
req = self._build_request(type, command_list)
if self.nxargs['connect_over_uds']:
self.connection.request('POST', req['url'], req['payload'], req['headers'])
response = self.connection.getresponse()
else:
response = self.connection(req['url'],
method='POST',
opts=req['opts'],
data=req['payload'],
header_dict=req['headers'],
decode=True,
decode_type='json',
**self.nxargs)
return self.parse_response(response, command_list)
def parse_response(self, response, command_list):
'''
Parse NX-API JSON response from the NX-OS device.
'''
# Check for 500 level NX-API Server Errors
if isinstance(response, collections.Iterable) and 'status' in response:
if int(response['status']) >= 500:
raise NxosError('{}'.format(response))
else:
raise NxosError('NX-API Request Not Supported: {}'.format(response))
if isinstance(response, collections.Iterable):
body = response['dict']
else:
body = response
if self.nxargs['connect_over_uds']:
body = json.loads(response.read().decode('utf-8'))
# Proceed with caution. The JSON may not be complete.
# Don't just return body['ins_api']['outputs']['output'] directly.
output = body.get('ins_api')
if output is None:
raise NxosClientError('Unexpected JSON output\n{0}'.format(body))
if output.get('outputs'):
output = output['outputs']
if output.get('output'):
output = output['output']
# The result list stores results for each command that was sent to
# nxapi.
result = []
# Keep track of successful commands using previous_commands list so
# they can be displayed if a specific command fails in a chain of
# commands.
previous_commands = []
# Make sure output and command_list lists to be processed in the
# subesequent loop.
if not isinstance(output, list):
output = [output]
if isinstance(command_list, string_types):
command_list = [cmd.strip() for cmd in command_list.split(';')]
if not isinstance(command_list, list):
command_list = [command_list]
for cmd_result, cmd in zip(output, command_list):
code = cmd_result.get('code')
msg = cmd_result.get('msg')
log.info('command %s:', cmd)
log.info('PARSE_RESPONSE: %s %s', code, msg)
if code == '400':
raise CommandExecutionError({
'rejected_input': cmd,
'code': code,
'message': msg,
'cli_error': cmd_result.get('clierror'),
'previous_commands': previous_commands,
})
elif code == '413':
raise NxosRequestNotSupported('Error 413: {}'.format(msg))
elif code != '200':
raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))
else:
previous_commands.append(cmd)
result.append(cmd_result['body'])
return result
|
saltstack/salt
|
salt/utils/nxos.py
|
NxapiClient.request
|
python
|
def request(self, type, command_list):
'''
Send NX-API JSON request to the NX-OS device.
'''
req = self._build_request(type, command_list)
if self.nxargs['connect_over_uds']:
self.connection.request('POST', req['url'], req['payload'], req['headers'])
response = self.connection.getresponse()
else:
response = self.connection(req['url'],
method='POST',
opts=req['opts'],
data=req['payload'],
header_dict=req['headers'],
decode=True,
decode_type='json',
**self.nxargs)
return self.parse_response(response, command_list)
|
Send NX-API JSON request to the NX-OS device.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L181-L199
|
[
"def _build_request(self, type, commands):\n '''\n Build NX-API JSON request.\n '''\n request = {}\n headers = {\n 'content-type': 'application/json',\n }\n if self.nxargs['connect_over_uds']:\n user = self.nxargs['cookie']\n headers['cookie'] = 'nxapi_auth=' + user + ':local'\n request['url'] = self.NXAPI_UDS_URI_PATH\n else:\n request['url'] = '{transport}://{host}:{port}{uri}'.format(\n transport=self.nxargs['transport'],\n host=self.nxargs['host'],\n port=self.nxargs['port'],\n uri=self.NXAPI_REMOTE_URI_PATH,\n )\n\n if isinstance(commands, (list, set, tuple)):\n commands = ' ; '.join(commands)\n payload = {}\n payload['ins_api'] = {\n 'version': self.NXAPI_VERSION,\n 'type': type,\n 'chunk': '0',\n 'sid': '1',\n 'input': commands,\n 'output_format': 'json',\n }\n request['headers'] = headers\n request['payload'] = json.dumps(payload)\n request['opts'] = {\n 'http_request_timeout': self.nxargs['timeout']\n }\n log.info('request: %s', request)\n return request\n",
"def parse_response(self, response, command_list):\n '''\n Parse NX-API JSON response from the NX-OS device.\n '''\n # Check for 500 level NX-API Server Errors\n if isinstance(response, collections.Iterable) and 'status' in response:\n if int(response['status']) >= 500:\n raise NxosError('{}'.format(response))\n else:\n raise NxosError('NX-API Request Not Supported: {}'.format(response))\n\n if isinstance(response, collections.Iterable):\n body = response['dict']\n else:\n body = response\n\n if self.nxargs['connect_over_uds']:\n body = json.loads(response.read().decode('utf-8'))\n\n # Proceed with caution. The JSON may not be complete.\n # Don't just return body['ins_api']['outputs']['output'] directly.\n output = body.get('ins_api')\n if output is None:\n raise NxosClientError('Unexpected JSON output\\n{0}'.format(body))\n if output.get('outputs'):\n output = output['outputs']\n if output.get('output'):\n output = output['output']\n\n # The result list stores results for each command that was sent to\n # nxapi.\n result = []\n # Keep track of successful commands using previous_commands list so\n # they can be displayed if a specific command fails in a chain of\n # commands.\n previous_commands = []\n\n # Make sure output and command_list lists to be processed in the\n # subesequent loop.\n if not isinstance(output, list):\n output = [output]\n if isinstance(command_list, string_types):\n command_list = [cmd.strip() for cmd in command_list.split(';')]\n if not isinstance(command_list, list):\n command_list = [command_list]\n\n for cmd_result, cmd in zip(output, command_list):\n code = cmd_result.get('code')\n msg = cmd_result.get('msg')\n log.info('command %s:', cmd)\n log.info('PARSE_RESPONSE: %s %s', code, msg)\n if code == '400':\n raise CommandExecutionError({\n 'rejected_input': cmd,\n 'code': code,\n 'message': msg,\n 'cli_error': cmd_result.get('clierror'),\n 'previous_commands': previous_commands,\n })\n elif code == '413':\n raise NxosRequestNotSupported('Error 413: {}'.format(msg))\n elif code != '200':\n raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))\n else:\n previous_commands.append(cmd)\n result.append(cmd_result['body'])\n\n return result\n"
] |
class NxapiClient(object):
'''
Class representing an NX-API client that connects over http(s) or
unix domain socket (UDS).
'''
# Location of unix domain socket for NX-API localhost
NXAPI_UDS = '/tmp/nginx_local/nginx_1_be_nxapi.sock'
# NXAPI listens for remote connections to "http(s)://<switch IP>/ins"
# NXAPI listens for local connections to "http(s)://<UDS>/ins_local"
NXAPI_REMOTE_URI_PATH = '/ins'
NXAPI_UDS_URI_PATH = '/ins_local'
NXAPI_VERSION = '1.0'
def __init__(self, **nxos_kwargs):
'''
Initialize NxapiClient() connection object. By default this connects
to the local unix domain socket (UDS). If http(s) is required to
connect to a remote device then
nxos_kwargs['host'],
nxos_kwargs['username'],
nxos_kwargs['password'],
nxos_kwargs['transport'],
nxos_kwargs['port'],
parameters must be provided.
'''
self.nxargs = self._prepare_conn_args(clean_kwargs(**nxos_kwargs))
# Default: Connect to unix domain socket on localhost.
if self.nxargs['connect_over_uds']:
if not os.path.exists(self.NXAPI_UDS):
raise NxosClientError("No host specified and no UDS found at {0}\n".format(self.NXAPI_UDS))
# Create UHTTPConnection object for NX-API communication over UDS.
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over unix domain socket')
self.connection = UHTTPConnection(self.NXAPI_UDS)
else:
# Remote connection - Proxy Minion, connect over http(s)
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over %s', self.nxargs['transport'])
self.connection = salt.utils.http.query
def _use_remote_connection(self, kwargs):
'''
Determine if connection is local or remote
'''
kwargs['host'] = kwargs.get('host')
kwargs['username'] = kwargs.get('username')
kwargs['password'] = kwargs.get('password')
if kwargs['host'] is None or \
kwargs['username'] is None or \
kwargs['password'] is None:
return False
else:
return True
def _prepare_conn_args(self, kwargs):
'''
Set connection arguments for remote or local connection.
'''
kwargs['connect_over_uds'] = True
kwargs['timeout'] = kwargs.get('timeout', 60)
kwargs['cookie'] = kwargs.get('cookie', 'admin')
if self._use_remote_connection(kwargs):
kwargs['transport'] = kwargs.get('transport', 'https')
if kwargs['transport'] == 'https':
kwargs['port'] = kwargs.get('port', 443)
else:
kwargs['port'] = kwargs.get('port', 80)
kwargs['verify'] = kwargs.get('verify', True)
if isinstance(kwargs['verify'], bool):
kwargs['verify_ssl'] = kwargs['verify']
else:
kwargs['ca_bundle'] = kwargs['verify']
kwargs['connect_over_uds'] = False
return kwargs
def _build_request(self, type, commands):
'''
Build NX-API JSON request.
'''
request = {}
headers = {
'content-type': 'application/json',
}
if self.nxargs['connect_over_uds']:
user = self.nxargs['cookie']
headers['cookie'] = 'nxapi_auth=' + user + ':local'
request['url'] = self.NXAPI_UDS_URI_PATH
else:
request['url'] = '{transport}://{host}:{port}{uri}'.format(
transport=self.nxargs['transport'],
host=self.nxargs['host'],
port=self.nxargs['port'],
uri=self.NXAPI_REMOTE_URI_PATH,
)
if isinstance(commands, (list, set, tuple)):
commands = ' ; '.join(commands)
payload = {}
payload['ins_api'] = {
'version': self.NXAPI_VERSION,
'type': type,
'chunk': '0',
'sid': '1',
'input': commands,
'output_format': 'json',
}
request['headers'] = headers
request['payload'] = json.dumps(payload)
request['opts'] = {
'http_request_timeout': self.nxargs['timeout']
}
log.info('request: %s', request)
return request
def parse_response(self, response, command_list):
'''
Parse NX-API JSON response from the NX-OS device.
'''
# Check for 500 level NX-API Server Errors
if isinstance(response, collections.Iterable) and 'status' in response:
if int(response['status']) >= 500:
raise NxosError('{}'.format(response))
else:
raise NxosError('NX-API Request Not Supported: {}'.format(response))
if isinstance(response, collections.Iterable):
body = response['dict']
else:
body = response
if self.nxargs['connect_over_uds']:
body = json.loads(response.read().decode('utf-8'))
# Proceed with caution. The JSON may not be complete.
# Don't just return body['ins_api']['outputs']['output'] directly.
output = body.get('ins_api')
if output is None:
raise NxosClientError('Unexpected JSON output\n{0}'.format(body))
if output.get('outputs'):
output = output['outputs']
if output.get('output'):
output = output['output']
# The result list stores results for each command that was sent to
# nxapi.
result = []
# Keep track of successful commands using previous_commands list so
# they can be displayed if a specific command fails in a chain of
# commands.
previous_commands = []
# Make sure output and command_list lists to be processed in the
# subesequent loop.
if not isinstance(output, list):
output = [output]
if isinstance(command_list, string_types):
command_list = [cmd.strip() for cmd in command_list.split(';')]
if not isinstance(command_list, list):
command_list = [command_list]
for cmd_result, cmd in zip(output, command_list):
code = cmd_result.get('code')
msg = cmd_result.get('msg')
log.info('command %s:', cmd)
log.info('PARSE_RESPONSE: %s %s', code, msg)
if code == '400':
raise CommandExecutionError({
'rejected_input': cmd,
'code': code,
'message': msg,
'cli_error': cmd_result.get('clierror'),
'previous_commands': previous_commands,
})
elif code == '413':
raise NxosRequestNotSupported('Error 413: {}'.format(msg))
elif code != '200':
raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))
else:
previous_commands.append(cmd)
result.append(cmd_result['body'])
return result
|
saltstack/salt
|
salt/utils/nxos.py
|
NxapiClient.parse_response
|
python
|
def parse_response(self, response, command_list):
'''
Parse NX-API JSON response from the NX-OS device.
'''
# Check for 500 level NX-API Server Errors
if isinstance(response, collections.Iterable) and 'status' in response:
if int(response['status']) >= 500:
raise NxosError('{}'.format(response))
else:
raise NxosError('NX-API Request Not Supported: {}'.format(response))
if isinstance(response, collections.Iterable):
body = response['dict']
else:
body = response
if self.nxargs['connect_over_uds']:
body = json.loads(response.read().decode('utf-8'))
# Proceed with caution. The JSON may not be complete.
# Don't just return body['ins_api']['outputs']['output'] directly.
output = body.get('ins_api')
if output is None:
raise NxosClientError('Unexpected JSON output\n{0}'.format(body))
if output.get('outputs'):
output = output['outputs']
if output.get('output'):
output = output['output']
# The result list stores results for each command that was sent to
# nxapi.
result = []
# Keep track of successful commands using previous_commands list so
# they can be displayed if a specific command fails in a chain of
# commands.
previous_commands = []
# Make sure output and command_list lists to be processed in the
# subesequent loop.
if not isinstance(output, list):
output = [output]
if isinstance(command_list, string_types):
command_list = [cmd.strip() for cmd in command_list.split(';')]
if not isinstance(command_list, list):
command_list = [command_list]
for cmd_result, cmd in zip(output, command_list):
code = cmd_result.get('code')
msg = cmd_result.get('msg')
log.info('command %s:', cmd)
log.info('PARSE_RESPONSE: %s %s', code, msg)
if code == '400':
raise CommandExecutionError({
'rejected_input': cmd,
'code': code,
'message': msg,
'cli_error': cmd_result.get('clierror'),
'previous_commands': previous_commands,
})
elif code == '413':
raise NxosRequestNotSupported('Error 413: {}'.format(msg))
elif code != '200':
raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))
else:
previous_commands.append(cmd)
result.append(cmd_result['body'])
return result
|
Parse NX-API JSON response from the NX-OS device.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nxos.py#L201-L268
| null |
class NxapiClient(object):
'''
Class representing an NX-API client that connects over http(s) or
unix domain socket (UDS).
'''
# Location of unix domain socket for NX-API localhost
NXAPI_UDS = '/tmp/nginx_local/nginx_1_be_nxapi.sock'
# NXAPI listens for remote connections to "http(s)://<switch IP>/ins"
# NXAPI listens for local connections to "http(s)://<UDS>/ins_local"
NXAPI_REMOTE_URI_PATH = '/ins'
NXAPI_UDS_URI_PATH = '/ins_local'
NXAPI_VERSION = '1.0'
def __init__(self, **nxos_kwargs):
'''
Initialize NxapiClient() connection object. By default this connects
to the local unix domain socket (UDS). If http(s) is required to
connect to a remote device then
nxos_kwargs['host'],
nxos_kwargs['username'],
nxos_kwargs['password'],
nxos_kwargs['transport'],
nxos_kwargs['port'],
parameters must be provided.
'''
self.nxargs = self._prepare_conn_args(clean_kwargs(**nxos_kwargs))
# Default: Connect to unix domain socket on localhost.
if self.nxargs['connect_over_uds']:
if not os.path.exists(self.NXAPI_UDS):
raise NxosClientError("No host specified and no UDS found at {0}\n".format(self.NXAPI_UDS))
# Create UHTTPConnection object for NX-API communication over UDS.
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over unix domain socket')
self.connection = UHTTPConnection(self.NXAPI_UDS)
else:
# Remote connection - Proxy Minion, connect over http(s)
log.info('Nxapi connection arguments: %s', self.nxargs)
log.info('Connecting over %s', self.nxargs['transport'])
self.connection = salt.utils.http.query
def _use_remote_connection(self, kwargs):
'''
Determine if connection is local or remote
'''
kwargs['host'] = kwargs.get('host')
kwargs['username'] = kwargs.get('username')
kwargs['password'] = kwargs.get('password')
if kwargs['host'] is None or \
kwargs['username'] is None or \
kwargs['password'] is None:
return False
else:
return True
def _prepare_conn_args(self, kwargs):
'''
Set connection arguments for remote or local connection.
'''
kwargs['connect_over_uds'] = True
kwargs['timeout'] = kwargs.get('timeout', 60)
kwargs['cookie'] = kwargs.get('cookie', 'admin')
if self._use_remote_connection(kwargs):
kwargs['transport'] = kwargs.get('transport', 'https')
if kwargs['transport'] == 'https':
kwargs['port'] = kwargs.get('port', 443)
else:
kwargs['port'] = kwargs.get('port', 80)
kwargs['verify'] = kwargs.get('verify', True)
if isinstance(kwargs['verify'], bool):
kwargs['verify_ssl'] = kwargs['verify']
else:
kwargs['ca_bundle'] = kwargs['verify']
kwargs['connect_over_uds'] = False
return kwargs
def _build_request(self, type, commands):
'''
Build NX-API JSON request.
'''
request = {}
headers = {
'content-type': 'application/json',
}
if self.nxargs['connect_over_uds']:
user = self.nxargs['cookie']
headers['cookie'] = 'nxapi_auth=' + user + ':local'
request['url'] = self.NXAPI_UDS_URI_PATH
else:
request['url'] = '{transport}://{host}:{port}{uri}'.format(
transport=self.nxargs['transport'],
host=self.nxargs['host'],
port=self.nxargs['port'],
uri=self.NXAPI_REMOTE_URI_PATH,
)
if isinstance(commands, (list, set, tuple)):
commands = ' ; '.join(commands)
payload = {}
payload['ins_api'] = {
'version': self.NXAPI_VERSION,
'type': type,
'chunk': '0',
'sid': '1',
'input': commands,
'output_format': 'json',
}
request['headers'] = headers
request['payload'] = json.dumps(payload)
request['opts'] = {
'http_request_timeout': self.nxargs['timeout']
}
log.info('request: %s', request)
return request
def request(self, type, command_list):
'''
Send NX-API JSON request to the NX-OS device.
'''
req = self._build_request(type, command_list)
if self.nxargs['connect_over_uds']:
self.connection.request('POST', req['url'], req['payload'], req['headers'])
response = self.connection.getresponse()
else:
response = self.connection(req['url'],
method='POST',
opts=req['opts'],
data=req['payload'],
header_dict=req['headers'],
decode=True,
decode_type='json',
**self.nxargs)
return self.parse_response(response, command_list)
|
saltstack/salt
|
salt/utils/powershell.py
|
get_modules
|
python
|
def get_modules():
'''
Get a list of the PowerShell modules which are potentially available to be
imported. The intent is to mimic the functionality of ``Get-Module
-ListAvailable | Select-Object -Expand Name``, without the delay of loading
PowerShell to do so.
Returns:
list: A list of modules available to Powershell
Example:
.. code-block:: python
import salt.utils.powershell
modules = salt.utils.powershell.get_modules()
'''
ret = list()
valid_extensions = ('.psd1', '.psm1', '.cdxml', '.xaml', '.dll')
# need to create an info function to get PS information including version
# __salt__ is not available from salt.utils... need to create a salt.util
# for the registry to avoid loading powershell to get the version
# not sure how to get the powershell version in linux outside of powershell
# if running powershell to get version need to use subprocess.Popen
# That information will be loaded here
# ps_version = info()['version_raw']
root_paths = []
home_dir = os.environ.get('HOME', os.environ.get('HOMEPATH'))
system_dir = '{0}\\System32'.format(os.environ.get('WINDIR', 'C:\\Windows'))
program_files = os.environ.get('ProgramFiles', 'C:\\Program Files')
default_paths = [
'{0}/.local/share/powershell/Modules'.format(home_dir),
# Once version is available, these can be enabled
# '/opt/microsoft/powershell/{0}/Modules'.format(ps_version),
# '/usr/local/microsoft/powershell/{0}/Modules'.format(ps_version),
'/usr/local/share/powershell/Modules',
'{0}\\WindowsPowerShell\\v1.0\\Modules\\'.format(system_dir),
'{0}\\WindowsPowerShell\\Modules'.format(program_files)]
default_paths = ';'.join(default_paths)
ps_module_path = os.environ.get('PSModulePath', default_paths)
# Check if defaults exist, add them if they do
ps_module_path = ps_module_path.split(';')
for item in ps_module_path:
if os.path.exists(item):
root_paths.append(item)
# Did we find any, if not log the error and return
if not root_paths:
log.error('Default paths not found')
return ret
for root_path in root_paths:
# only recurse directories
if not os.path.isdir(root_path):
continue
# get a list of all files in the root_path
for root_dir, sub_dirs, file_names in salt.utils.path.os_walk(root_path):
for file_name in file_names:
base_name, file_extension = os.path.splitext(file_name)
# If a module file or module manifest is present, check if
# the base name matches the directory name.
if file_extension.lower() in valid_extensions:
dir_name = os.path.basename(os.path.normpath(root_dir))
# Stop recursion once we find a match, and use
# the capitalization from the directory name.
if dir_name not in ret and \
base_name.lower() == dir_name.lower():
del sub_dirs[:]
ret.append(dir_name)
return ret
|
Get a list of the PowerShell modules which are potentially available to be
imported. The intent is to mimic the functionality of ``Get-Module
-ListAvailable | Select-Object -Expand Name``, without the delay of loading
PowerShell to do so.
Returns:
list: A list of modules available to Powershell
Example:
.. code-block:: python
import salt.utils.powershell
modules = salt.utils.powershell.get_modules()
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/powershell.py#L46-L124
|
[
"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 -*-
'''
Common functions for working with powershell
.. note:: The PSModulePath environment variable should be set to the default
location for PowerShell modules. This applies to all OS'es that support
powershell. If not set, then Salt will attempt to use some default paths.
If Salt can't find your modules, ensure that the PSModulePath is set and
pointing to all locations of your Powershell modules.
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import salt.utils.path
log = logging.getLogger(__name__)
def module_exists(name):
'''
Check if a module exists on the system.
Use this utility instead of attempting to import the module with powershell.
Using powershell to try to import the module is expensive.
Args:
name (str):
The name of the module to check
Returns:
bool: True if present, otherwise returns False
Example:
.. code-block:: python
import salt.utils.powershell
exists = salt.utils.powershell.module_exists('ServerManager')
'''
return name in get_modules()
|
saltstack/salt
|
salt/modules/icinga2.py
|
generate_cert
|
python
|
def generate_cert(domain):
'''
Generate an icinga2 client certificate and key.
Returns::
icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_cert domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "new-cert", "--cn", domain, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.crt".format(get_certs_path(), domain)], python_shell=False)
return result
|
Generate an icinga2 client certificate and key.
Returns::
icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_cert domain.tld
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/icinga2.py#L53-L68
|
[
"def get_certs_path():\n icinga2_output = __salt__['cmd.run_all']([salt.utils.path.which('icinga2'),\n \"--version\"], python_shell=False)\n version = re.search(r'r\\d+\\.\\d+', icinga2_output['stdout']).group(0)\n # Return new certs path for icinga2 >= 2.8\n if int(version.split('.')[1]) >= 8:\n return '/var/lib/icinga2/certs/'\n # Keep backwords compatibility with older icinga2\n return '/etc/icinga2/pki/'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide icinga2 compatibility to salt.
.. versionadded:: 2017.7.0
:depends: - icinga2 server
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.platform
from salt.utils.icinga2 import get_certs_path
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load this module if the mysql libraries exist
'''
# TODO: This could work on windows with some love
if salt.utils.platform.is_windows():
return (False, 'The module cannot be loaded on windows.')
if salt.utils.path.which('icinga2'):
return True
return (False, 'Icinga2 not installed.')
def generate_ticket(domain):
'''
Generate and save an icinga2 ticket.
Returns::
icinga2 pki ticket --cn domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_ticket domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "ticket", "--cn", domain], python_shell=False)
return result
def save_cert(domain, master):
'''
Save the certificate for master icinga2 node.
Returns::
icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.save_cert domain.tld master.domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "save-cert", "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.cert".format(get_certs_path(), domain), "--trustedcert",
"{0}trusted-master.crt".format(get_certs_path()), "--host", master], python_shell=False)
return result
def request_cert(domain, master, ticket, port):
'''
Request CA cert from master icinga2 node.
Returns::
icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \
/etc/icinga2/pki/trusted-master.crt --ca /etc/icinga2/pki/ca.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.request_cert domain.tld master.domain.tld TICKET_ID
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "request", "--host", master, "--port", port, "--ticket", ticket, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert",
"{0}{1}.crt".format(get_certs_path(), domain), "--trustedcert", "{0}trusted-master.crt".format(get_certs_path()), "--ca", "{0}ca.crt".format(get_certs_path())], python_shell=False)
return result
def node_setup(domain, master, ticket):
'''
Setup the icinga2 node.
Returns::
icinga2 node setup --ticket TICKET_ID --endpoint master.domain.tld --zone domain.tld --master_host master.domain.tld --trustedcert \
/etc/icinga2/pki/trusted-master.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.node_setup domain.tld master.domain.tld TICKET_ID
'''
result = __salt__['cmd.run_all'](["icinga2", "node", "setup", "--ticket", ticket, "--endpoint", master, "--zone", domain, "--master_host", master, "--trustedcert", "{0}trusted-master.crt".format(get_certs_path())],
python_shell=False)
return result
|
saltstack/salt
|
salt/modules/icinga2.py
|
save_cert
|
python
|
def save_cert(domain, master):
'''
Save the certificate for master icinga2 node.
Returns::
icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.save_cert domain.tld master.domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "save-cert", "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.cert".format(get_certs_path(), domain), "--trustedcert",
"{0}trusted-master.crt".format(get_certs_path()), "--host", master], python_shell=False)
return result
|
Save the certificate for master icinga2 node.
Returns::
icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.save_cert domain.tld master.domain.tld
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/icinga2.py#L71-L87
|
[
"def get_certs_path():\n icinga2_output = __salt__['cmd.run_all']([salt.utils.path.which('icinga2'),\n \"--version\"], python_shell=False)\n version = re.search(r'r\\d+\\.\\d+', icinga2_output['stdout']).group(0)\n # Return new certs path for icinga2 >= 2.8\n if int(version.split('.')[1]) >= 8:\n return '/var/lib/icinga2/certs/'\n # Keep backwords compatibility with older icinga2\n return '/etc/icinga2/pki/'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide icinga2 compatibility to salt.
.. versionadded:: 2017.7.0
:depends: - icinga2 server
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.platform
from salt.utils.icinga2 import get_certs_path
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load this module if the mysql libraries exist
'''
# TODO: This could work on windows with some love
if salt.utils.platform.is_windows():
return (False, 'The module cannot be loaded on windows.')
if salt.utils.path.which('icinga2'):
return True
return (False, 'Icinga2 not installed.')
def generate_ticket(domain):
'''
Generate and save an icinga2 ticket.
Returns::
icinga2 pki ticket --cn domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_ticket domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "ticket", "--cn", domain], python_shell=False)
return result
def generate_cert(domain):
'''
Generate an icinga2 client certificate and key.
Returns::
icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_cert domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "new-cert", "--cn", domain, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.crt".format(get_certs_path(), domain)], python_shell=False)
return result
def request_cert(domain, master, ticket, port):
'''
Request CA cert from master icinga2 node.
Returns::
icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \
/etc/icinga2/pki/trusted-master.crt --ca /etc/icinga2/pki/ca.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.request_cert domain.tld master.domain.tld TICKET_ID
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "request", "--host", master, "--port", port, "--ticket", ticket, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert",
"{0}{1}.crt".format(get_certs_path(), domain), "--trustedcert", "{0}trusted-master.crt".format(get_certs_path()), "--ca", "{0}ca.crt".format(get_certs_path())], python_shell=False)
return result
def node_setup(domain, master, ticket):
'''
Setup the icinga2 node.
Returns::
icinga2 node setup --ticket TICKET_ID --endpoint master.domain.tld --zone domain.tld --master_host master.domain.tld --trustedcert \
/etc/icinga2/pki/trusted-master.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.node_setup domain.tld master.domain.tld TICKET_ID
'''
result = __salt__['cmd.run_all'](["icinga2", "node", "setup", "--ticket", ticket, "--endpoint", master, "--zone", domain, "--master_host", master, "--trustedcert", "{0}trusted-master.crt".format(get_certs_path())],
python_shell=False)
return result
|
saltstack/salt
|
salt/modules/icinga2.py
|
request_cert
|
python
|
def request_cert(domain, master, ticket, port):
'''
Request CA cert from master icinga2 node.
Returns::
icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \
/etc/icinga2/pki/trusted-master.crt --ca /etc/icinga2/pki/ca.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.request_cert domain.tld master.domain.tld TICKET_ID
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "request", "--host", master, "--port", port, "--ticket", ticket, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert",
"{0}{1}.crt".format(get_certs_path(), domain), "--trustedcert", "{0}trusted-master.crt".format(get_certs_path()), "--ca", "{0}ca.crt".format(get_certs_path())], python_shell=False)
return result
|
Request CA cert from master icinga2 node.
Returns::
icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \
/etc/icinga2/pki/trusted-master.crt --ca /etc/icinga2/pki/ca.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.request_cert domain.tld master.domain.tld TICKET_ID
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/icinga2.py#L90-L107
|
[
"def get_certs_path():\n icinga2_output = __salt__['cmd.run_all']([salt.utils.path.which('icinga2'),\n \"--version\"], python_shell=False)\n version = re.search(r'r\\d+\\.\\d+', icinga2_output['stdout']).group(0)\n # Return new certs path for icinga2 >= 2.8\n if int(version.split('.')[1]) >= 8:\n return '/var/lib/icinga2/certs/'\n # Keep backwords compatibility with older icinga2\n return '/etc/icinga2/pki/'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide icinga2 compatibility to salt.
.. versionadded:: 2017.7.0
:depends: - icinga2 server
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.platform
from salt.utils.icinga2 import get_certs_path
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load this module if the mysql libraries exist
'''
# TODO: This could work on windows with some love
if salt.utils.platform.is_windows():
return (False, 'The module cannot be loaded on windows.')
if salt.utils.path.which('icinga2'):
return True
return (False, 'Icinga2 not installed.')
def generate_ticket(domain):
'''
Generate and save an icinga2 ticket.
Returns::
icinga2 pki ticket --cn domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_ticket domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "ticket", "--cn", domain], python_shell=False)
return result
def generate_cert(domain):
'''
Generate an icinga2 client certificate and key.
Returns::
icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_cert domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "new-cert", "--cn", domain, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.crt".format(get_certs_path(), domain)], python_shell=False)
return result
def save_cert(domain, master):
'''
Save the certificate for master icinga2 node.
Returns::
icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.save_cert domain.tld master.domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "save-cert", "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.cert".format(get_certs_path(), domain), "--trustedcert",
"{0}trusted-master.crt".format(get_certs_path()), "--host", master], python_shell=False)
return result
def node_setup(domain, master, ticket):
'''
Setup the icinga2 node.
Returns::
icinga2 node setup --ticket TICKET_ID --endpoint master.domain.tld --zone domain.tld --master_host master.domain.tld --trustedcert \
/etc/icinga2/pki/trusted-master.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.node_setup domain.tld master.domain.tld TICKET_ID
'''
result = __salt__['cmd.run_all'](["icinga2", "node", "setup", "--ticket", ticket, "--endpoint", master, "--zone", domain, "--master_host", master, "--trustedcert", "{0}trusted-master.crt".format(get_certs_path())],
python_shell=False)
return result
|
saltstack/salt
|
salt/modules/icinga2.py
|
node_setup
|
python
|
def node_setup(domain, master, ticket):
'''
Setup the icinga2 node.
Returns::
icinga2 node setup --ticket TICKET_ID --endpoint master.domain.tld --zone domain.tld --master_host master.domain.tld --trustedcert \
/etc/icinga2/pki/trusted-master.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.node_setup domain.tld master.domain.tld TICKET_ID
'''
result = __salt__['cmd.run_all'](["icinga2", "node", "setup", "--ticket", ticket, "--endpoint", master, "--zone", domain, "--master_host", master, "--trustedcert", "{0}trusted-master.crt".format(get_certs_path())],
python_shell=False)
return result
|
Setup the icinga2 node.
Returns::
icinga2 node setup --ticket TICKET_ID --endpoint master.domain.tld --zone domain.tld --master_host master.domain.tld --trustedcert \
/etc/icinga2/pki/trusted-master.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.node_setup domain.tld master.domain.tld TICKET_ID
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/icinga2.py#L110-L127
|
[
"def get_certs_path():\n icinga2_output = __salt__['cmd.run_all']([salt.utils.path.which('icinga2'),\n \"--version\"], python_shell=False)\n version = re.search(r'r\\d+\\.\\d+', icinga2_output['stdout']).group(0)\n # Return new certs path for icinga2 >= 2.8\n if int(version.split('.')[1]) >= 8:\n return '/var/lib/icinga2/certs/'\n # Keep backwords compatibility with older icinga2\n return '/etc/icinga2/pki/'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide icinga2 compatibility to salt.
.. versionadded:: 2017.7.0
:depends: - icinga2 server
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.path
import salt.utils.platform
from salt.utils.icinga2 import get_certs_path
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load this module if the mysql libraries exist
'''
# TODO: This could work on windows with some love
if salt.utils.platform.is_windows():
return (False, 'The module cannot be loaded on windows.')
if salt.utils.path.which('icinga2'):
return True
return (False, 'Icinga2 not installed.')
def generate_ticket(domain):
'''
Generate and save an icinga2 ticket.
Returns::
icinga2 pki ticket --cn domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_ticket domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "ticket", "--cn", domain], python_shell=False)
return result
def generate_cert(domain):
'''
Generate an icinga2 client certificate and key.
Returns::
icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_cert domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "new-cert", "--cn", domain, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.crt".format(get_certs_path(), domain)], python_shell=False)
return result
def save_cert(domain, master):
'''
Save the certificate for master icinga2 node.
Returns::
icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld
CLI Example:
.. code-block:: bash
salt '*' icinga2.save_cert domain.tld master.domain.tld
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "save-cert", "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.cert".format(get_certs_path(), domain), "--trustedcert",
"{0}trusted-master.crt".format(get_certs_path()), "--host", master], python_shell=False)
return result
def request_cert(domain, master, ticket, port):
'''
Request CA cert from master icinga2 node.
Returns::
icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \
/etc/icinga2/pki/trusted-master.crt --ca /etc/icinga2/pki/ca.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.request_cert domain.tld master.domain.tld TICKET_ID
'''
result = __salt__['cmd.run_all'](["icinga2", "pki", "request", "--host", master, "--port", port, "--ticket", ticket, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert",
"{0}{1}.crt".format(get_certs_path(), domain), "--trustedcert", "{0}trusted-master.crt".format(get_certs_path()), "--ca", "{0}ca.crt".format(get_certs_path())], python_shell=False)
return result
|
saltstack/salt
|
salt/roster/terraform.py
|
_handle_salt_host_resource
|
python
|
def _handle_salt_host_resource(resource):
'''
Handles salt_host resources.
See https://github.com/dmacvicar/terraform-provider-salt
Returns roster attributes for the resource or None
'''
ret = {}
attrs = resource.get('primary', {}).get('attributes', {})
ret[MINION_ID] = attrs.get(MINION_ID)
valid_attrs = set(attrs.keys()).intersection(TF_ROSTER_ATTRS.keys())
for attr in valid_attrs:
ret[attr] = _cast_output_to_type(attrs.get(attr), TF_ROSTER_ATTRS.get(attr))
return ret
|
Handles salt_host resources.
See https://github.com/dmacvicar/terraform-provider-salt
Returns roster attributes for the resource or None
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L83-L96
| null |
# -*- coding: utf-8 -*-
'''
Dynamic roster from terraform current state
===========================================
This roster module allows you dynamically generate the roster from the terraform
resources defined with the `Terraform Salt`_ provider.
It exposes all salt_host resources with the same attributes to the salt-ssh
roster, making it completely independent of the type of terraform resource, and
providing the integration using terraform constructs with interpolation.
Basic Example
-------------
Given a simple salt-ssh tree with a Saltfile:
.. code-block:: yaml
salt-ssh:
config_dir: etc/salt
max_procs: 30
wipe_ssh: True
and ``etc/salt/master``:
.. code-block:: yaml
root_dir: .
file_roots:
base:
- srv/salt
pillar_roots:
base:
- srv/pillar
roster: terraform
In the same folder as your ``Saltfile``, create terraform file with resources
like cloud instances, virtual machines, etc. For every single one of those that
you want to manage with Salt, create a ``salt_host`` resource:
.. code-block:: text
resource "salt_host" "dbminion" {
salt_id = "dbserver"
host = "${libvirt_domain.vm-db.network_interface.0.addresses.0}"
user = "root"
passwd = "linux"
}
You can use the count attribute to create multiple roster entries with a single
definition. Please refer to the `Terraform Salt`_ provider for more detailed
examples.
.. _Terraform Salt: https://github.com/dmacvicar/terraform-provider-salt
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import os.path
# Import Salt libs
import salt.utils.files
import salt.utils.json
log = logging.getLogger(__name__)
TF_OUTPUT_PREFIX = 'salt.roster.'
TF_ROSTER_ATTRS = {'host': 's',
'user': 's',
'passwd': 's',
'port': 'i',
'sudo': 'b',
'sudo_user': 's',
'tty': 'b', 'priv': 's',
'timeout': 'i',
'minion_opts': 'm',
'thin_dir': 's',
'cmd_umask': 'i'}
MINION_ID = 'salt_id'
def _add_ssh_key(ret):
'''
Setups the salt-ssh minion to be accessed with salt-ssh default key
'''
priv = None
if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = __opts__.get(
'ssh_priv',
os.path.abspath(os.path.join(
__opts__['pki_dir'],
'ssh',
'salt-ssh.rsa'
))
)
if priv and os.path.isfile(priv):
ret['priv'] = priv
def _cast_output_to_type(value, typ):
'''cast the value depending on the terraform type'''
if typ == 'b':
return bool(value)
if typ == 'i':
return int(value)
return value
def _parse_state_file(state_file_path='terraform.tfstate'):
'''
Parses the terraform state file passing different resource types to the right handler
'''
ret = {}
with salt.utils.files.fopen(state_file_path, 'r') as fh_:
tfstate = salt.utils.json.load(fh_)
modules = tfstate.get('modules')
if not modules:
log.error('Malformed tfstate file. No modules found')
return ret
for module in modules:
resources = module.get('resources', [])
for resource_name, resource in salt.ext.six.iteritems(resources):
roster_entry = None
if resource['type'] == 'salt_host':
roster_entry = _handle_salt_host_resource(resource)
if not roster_entry:
continue
minion_id = roster_entry.get(MINION_ID, resource.get('id'))
if not minion_id:
continue
if MINION_ID in roster_entry:
del roster_entry[MINION_ID]
_add_ssh_key(roster_entry)
ret[minion_id] = roster_entry
return ret
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613
'''
Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate
'''
roster_file = os.path.abspath('terraform.tfstate')
if __opts__.get('roster_file'):
roster_file = os.path.abspath(__opts__['roster_file'])
if not os.path.isfile(roster_file):
log.error("Can't find terraform state file '%s'", roster_file)
return {}
log.debug('terraform roster: using %s state file', roster_file)
if not roster_file.endswith('.tfstate'):
log.error("Terraform roster can only be used with terraform state files")
return {}
raw = _parse_state_file(roster_file)
log.debug('%s hosts in terraform state file', len(raw))
return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
|
saltstack/salt
|
salt/roster/terraform.py
|
_add_ssh_key
|
python
|
def _add_ssh_key(ret):
'''
Setups the salt-ssh minion to be accessed with salt-ssh default key
'''
priv = None
if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = __opts__.get(
'ssh_priv',
os.path.abspath(os.path.join(
__opts__['pki_dir'],
'ssh',
'salt-ssh.rsa'
))
)
if priv and os.path.isfile(priv):
ret['priv'] = priv
|
Setups the salt-ssh minion to be accessed with salt-ssh default key
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L99-L116
| null |
# -*- coding: utf-8 -*-
'''
Dynamic roster from terraform current state
===========================================
This roster module allows you dynamically generate the roster from the terraform
resources defined with the `Terraform Salt`_ provider.
It exposes all salt_host resources with the same attributes to the salt-ssh
roster, making it completely independent of the type of terraform resource, and
providing the integration using terraform constructs with interpolation.
Basic Example
-------------
Given a simple salt-ssh tree with a Saltfile:
.. code-block:: yaml
salt-ssh:
config_dir: etc/salt
max_procs: 30
wipe_ssh: True
and ``etc/salt/master``:
.. code-block:: yaml
root_dir: .
file_roots:
base:
- srv/salt
pillar_roots:
base:
- srv/pillar
roster: terraform
In the same folder as your ``Saltfile``, create terraform file with resources
like cloud instances, virtual machines, etc. For every single one of those that
you want to manage with Salt, create a ``salt_host`` resource:
.. code-block:: text
resource "salt_host" "dbminion" {
salt_id = "dbserver"
host = "${libvirt_domain.vm-db.network_interface.0.addresses.0}"
user = "root"
passwd = "linux"
}
You can use the count attribute to create multiple roster entries with a single
definition. Please refer to the `Terraform Salt`_ provider for more detailed
examples.
.. _Terraform Salt: https://github.com/dmacvicar/terraform-provider-salt
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import os.path
# Import Salt libs
import salt.utils.files
import salt.utils.json
log = logging.getLogger(__name__)
TF_OUTPUT_PREFIX = 'salt.roster.'
TF_ROSTER_ATTRS = {'host': 's',
'user': 's',
'passwd': 's',
'port': 'i',
'sudo': 'b',
'sudo_user': 's',
'tty': 'b', 'priv': 's',
'timeout': 'i',
'minion_opts': 'm',
'thin_dir': 's',
'cmd_umask': 'i'}
MINION_ID = 'salt_id'
def _handle_salt_host_resource(resource):
'''
Handles salt_host resources.
See https://github.com/dmacvicar/terraform-provider-salt
Returns roster attributes for the resource or None
'''
ret = {}
attrs = resource.get('primary', {}).get('attributes', {})
ret[MINION_ID] = attrs.get(MINION_ID)
valid_attrs = set(attrs.keys()).intersection(TF_ROSTER_ATTRS.keys())
for attr in valid_attrs:
ret[attr] = _cast_output_to_type(attrs.get(attr), TF_ROSTER_ATTRS.get(attr))
return ret
def _cast_output_to_type(value, typ):
'''cast the value depending on the terraform type'''
if typ == 'b':
return bool(value)
if typ == 'i':
return int(value)
return value
def _parse_state_file(state_file_path='terraform.tfstate'):
'''
Parses the terraform state file passing different resource types to the right handler
'''
ret = {}
with salt.utils.files.fopen(state_file_path, 'r') as fh_:
tfstate = salt.utils.json.load(fh_)
modules = tfstate.get('modules')
if not modules:
log.error('Malformed tfstate file. No modules found')
return ret
for module in modules:
resources = module.get('resources', [])
for resource_name, resource in salt.ext.six.iteritems(resources):
roster_entry = None
if resource['type'] == 'salt_host':
roster_entry = _handle_salt_host_resource(resource)
if not roster_entry:
continue
minion_id = roster_entry.get(MINION_ID, resource.get('id'))
if not minion_id:
continue
if MINION_ID in roster_entry:
del roster_entry[MINION_ID]
_add_ssh_key(roster_entry)
ret[minion_id] = roster_entry
return ret
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613
'''
Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate
'''
roster_file = os.path.abspath('terraform.tfstate')
if __opts__.get('roster_file'):
roster_file = os.path.abspath(__opts__['roster_file'])
if not os.path.isfile(roster_file):
log.error("Can't find terraform state file '%s'", roster_file)
return {}
log.debug('terraform roster: using %s state file', roster_file)
if not roster_file.endswith('.tfstate'):
log.error("Terraform roster can only be used with terraform state files")
return {}
raw = _parse_state_file(roster_file)
log.debug('%s hosts in terraform state file', len(raw))
return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
|
saltstack/salt
|
salt/roster/terraform.py
|
_cast_output_to_type
|
python
|
def _cast_output_to_type(value, typ):
'''cast the value depending on the terraform type'''
if typ == 'b':
return bool(value)
if typ == 'i':
return int(value)
return value
|
cast the value depending on the terraform type
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L119-L125
| null |
# -*- coding: utf-8 -*-
'''
Dynamic roster from terraform current state
===========================================
This roster module allows you dynamically generate the roster from the terraform
resources defined with the `Terraform Salt`_ provider.
It exposes all salt_host resources with the same attributes to the salt-ssh
roster, making it completely independent of the type of terraform resource, and
providing the integration using terraform constructs with interpolation.
Basic Example
-------------
Given a simple salt-ssh tree with a Saltfile:
.. code-block:: yaml
salt-ssh:
config_dir: etc/salt
max_procs: 30
wipe_ssh: True
and ``etc/salt/master``:
.. code-block:: yaml
root_dir: .
file_roots:
base:
- srv/salt
pillar_roots:
base:
- srv/pillar
roster: terraform
In the same folder as your ``Saltfile``, create terraform file with resources
like cloud instances, virtual machines, etc. For every single one of those that
you want to manage with Salt, create a ``salt_host`` resource:
.. code-block:: text
resource "salt_host" "dbminion" {
salt_id = "dbserver"
host = "${libvirt_domain.vm-db.network_interface.0.addresses.0}"
user = "root"
passwd = "linux"
}
You can use the count attribute to create multiple roster entries with a single
definition. Please refer to the `Terraform Salt`_ provider for more detailed
examples.
.. _Terraform Salt: https://github.com/dmacvicar/terraform-provider-salt
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import os.path
# Import Salt libs
import salt.utils.files
import salt.utils.json
log = logging.getLogger(__name__)
TF_OUTPUT_PREFIX = 'salt.roster.'
TF_ROSTER_ATTRS = {'host': 's',
'user': 's',
'passwd': 's',
'port': 'i',
'sudo': 'b',
'sudo_user': 's',
'tty': 'b', 'priv': 's',
'timeout': 'i',
'minion_opts': 'm',
'thin_dir': 's',
'cmd_umask': 'i'}
MINION_ID = 'salt_id'
def _handle_salt_host_resource(resource):
'''
Handles salt_host resources.
See https://github.com/dmacvicar/terraform-provider-salt
Returns roster attributes for the resource or None
'''
ret = {}
attrs = resource.get('primary', {}).get('attributes', {})
ret[MINION_ID] = attrs.get(MINION_ID)
valid_attrs = set(attrs.keys()).intersection(TF_ROSTER_ATTRS.keys())
for attr in valid_attrs:
ret[attr] = _cast_output_to_type(attrs.get(attr), TF_ROSTER_ATTRS.get(attr))
return ret
def _add_ssh_key(ret):
'''
Setups the salt-ssh minion to be accessed with salt-ssh default key
'''
priv = None
if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = __opts__.get(
'ssh_priv',
os.path.abspath(os.path.join(
__opts__['pki_dir'],
'ssh',
'salt-ssh.rsa'
))
)
if priv and os.path.isfile(priv):
ret['priv'] = priv
def _parse_state_file(state_file_path='terraform.tfstate'):
'''
Parses the terraform state file passing different resource types to the right handler
'''
ret = {}
with salt.utils.files.fopen(state_file_path, 'r') as fh_:
tfstate = salt.utils.json.load(fh_)
modules = tfstate.get('modules')
if not modules:
log.error('Malformed tfstate file. No modules found')
return ret
for module in modules:
resources = module.get('resources', [])
for resource_name, resource in salt.ext.six.iteritems(resources):
roster_entry = None
if resource['type'] == 'salt_host':
roster_entry = _handle_salt_host_resource(resource)
if not roster_entry:
continue
minion_id = roster_entry.get(MINION_ID, resource.get('id'))
if not minion_id:
continue
if MINION_ID in roster_entry:
del roster_entry[MINION_ID]
_add_ssh_key(roster_entry)
ret[minion_id] = roster_entry
return ret
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613
'''
Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate
'''
roster_file = os.path.abspath('terraform.tfstate')
if __opts__.get('roster_file'):
roster_file = os.path.abspath(__opts__['roster_file'])
if not os.path.isfile(roster_file):
log.error("Can't find terraform state file '%s'", roster_file)
return {}
log.debug('terraform roster: using %s state file', roster_file)
if not roster_file.endswith('.tfstate'):
log.error("Terraform roster can only be used with terraform state files")
return {}
raw = _parse_state_file(roster_file)
log.debug('%s hosts in terraform state file', len(raw))
return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
|
saltstack/salt
|
salt/roster/terraform.py
|
_parse_state_file
|
python
|
def _parse_state_file(state_file_path='terraform.tfstate'):
'''
Parses the terraform state file passing different resource types to the right handler
'''
ret = {}
with salt.utils.files.fopen(state_file_path, 'r') as fh_:
tfstate = salt.utils.json.load(fh_)
modules = tfstate.get('modules')
if not modules:
log.error('Malformed tfstate file. No modules found')
return ret
for module in modules:
resources = module.get('resources', [])
for resource_name, resource in salt.ext.six.iteritems(resources):
roster_entry = None
if resource['type'] == 'salt_host':
roster_entry = _handle_salt_host_resource(resource)
if not roster_entry:
continue
minion_id = roster_entry.get(MINION_ID, resource.get('id'))
if not minion_id:
continue
if MINION_ID in roster_entry:
del roster_entry[MINION_ID]
_add_ssh_key(roster_entry)
ret[minion_id] = roster_entry
return ret
|
Parses the terraform state file passing different resource types to the right handler
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L128-L159
| null |
# -*- coding: utf-8 -*-
'''
Dynamic roster from terraform current state
===========================================
This roster module allows you dynamically generate the roster from the terraform
resources defined with the `Terraform Salt`_ provider.
It exposes all salt_host resources with the same attributes to the salt-ssh
roster, making it completely independent of the type of terraform resource, and
providing the integration using terraform constructs with interpolation.
Basic Example
-------------
Given a simple salt-ssh tree with a Saltfile:
.. code-block:: yaml
salt-ssh:
config_dir: etc/salt
max_procs: 30
wipe_ssh: True
and ``etc/salt/master``:
.. code-block:: yaml
root_dir: .
file_roots:
base:
- srv/salt
pillar_roots:
base:
- srv/pillar
roster: terraform
In the same folder as your ``Saltfile``, create terraform file with resources
like cloud instances, virtual machines, etc. For every single one of those that
you want to manage with Salt, create a ``salt_host`` resource:
.. code-block:: text
resource "salt_host" "dbminion" {
salt_id = "dbserver"
host = "${libvirt_domain.vm-db.network_interface.0.addresses.0}"
user = "root"
passwd = "linux"
}
You can use the count attribute to create multiple roster entries with a single
definition. Please refer to the `Terraform Salt`_ provider for more detailed
examples.
.. _Terraform Salt: https://github.com/dmacvicar/terraform-provider-salt
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import os.path
# Import Salt libs
import salt.utils.files
import salt.utils.json
log = logging.getLogger(__name__)
TF_OUTPUT_PREFIX = 'salt.roster.'
TF_ROSTER_ATTRS = {'host': 's',
'user': 's',
'passwd': 's',
'port': 'i',
'sudo': 'b',
'sudo_user': 's',
'tty': 'b', 'priv': 's',
'timeout': 'i',
'minion_opts': 'm',
'thin_dir': 's',
'cmd_umask': 'i'}
MINION_ID = 'salt_id'
def _handle_salt_host_resource(resource):
'''
Handles salt_host resources.
See https://github.com/dmacvicar/terraform-provider-salt
Returns roster attributes for the resource or None
'''
ret = {}
attrs = resource.get('primary', {}).get('attributes', {})
ret[MINION_ID] = attrs.get(MINION_ID)
valid_attrs = set(attrs.keys()).intersection(TF_ROSTER_ATTRS.keys())
for attr in valid_attrs:
ret[attr] = _cast_output_to_type(attrs.get(attr), TF_ROSTER_ATTRS.get(attr))
return ret
def _add_ssh_key(ret):
'''
Setups the salt-ssh minion to be accessed with salt-ssh default key
'''
priv = None
if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = __opts__.get(
'ssh_priv',
os.path.abspath(os.path.join(
__opts__['pki_dir'],
'ssh',
'salt-ssh.rsa'
))
)
if priv and os.path.isfile(priv):
ret['priv'] = priv
def _cast_output_to_type(value, typ):
'''cast the value depending on the terraform type'''
if typ == 'b':
return bool(value)
if typ == 'i':
return int(value)
return value
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613
'''
Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate
'''
roster_file = os.path.abspath('terraform.tfstate')
if __opts__.get('roster_file'):
roster_file = os.path.abspath(__opts__['roster_file'])
if not os.path.isfile(roster_file):
log.error("Can't find terraform state file '%s'", roster_file)
return {}
log.debug('terraform roster: using %s state file', roster_file)
if not roster_file.endswith('.tfstate'):
log.error("Terraform roster can only be used with terraform state files")
return {}
raw = _parse_state_file(roster_file)
log.debug('%s hosts in terraform state file', len(raw))
return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
|
saltstack/salt
|
salt/roster/terraform.py
|
targets
|
python
|
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613
'''
Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate
'''
roster_file = os.path.abspath('terraform.tfstate')
if __opts__.get('roster_file'):
roster_file = os.path.abspath(__opts__['roster_file'])
if not os.path.isfile(roster_file):
log.error("Can't find terraform state file '%s'", roster_file)
return {}
log.debug('terraform roster: using %s state file', roster_file)
if not roster_file.endswith('.tfstate'):
log.error("Terraform roster can only be used with terraform state files")
return {}
raw = _parse_state_file(roster_file)
log.debug('%s hosts in terraform state file', len(raw))
return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
|
Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L162-L182
| null |
# -*- coding: utf-8 -*-
'''
Dynamic roster from terraform current state
===========================================
This roster module allows you dynamically generate the roster from the terraform
resources defined with the `Terraform Salt`_ provider.
It exposes all salt_host resources with the same attributes to the salt-ssh
roster, making it completely independent of the type of terraform resource, and
providing the integration using terraform constructs with interpolation.
Basic Example
-------------
Given a simple salt-ssh tree with a Saltfile:
.. code-block:: yaml
salt-ssh:
config_dir: etc/salt
max_procs: 30
wipe_ssh: True
and ``etc/salt/master``:
.. code-block:: yaml
root_dir: .
file_roots:
base:
- srv/salt
pillar_roots:
base:
- srv/pillar
roster: terraform
In the same folder as your ``Saltfile``, create terraform file with resources
like cloud instances, virtual machines, etc. For every single one of those that
you want to manage with Salt, create a ``salt_host`` resource:
.. code-block:: text
resource "salt_host" "dbminion" {
salt_id = "dbserver"
host = "${libvirt_domain.vm-db.network_interface.0.addresses.0}"
user = "root"
passwd = "linux"
}
You can use the count attribute to create multiple roster entries with a single
definition. Please refer to the `Terraform Salt`_ provider for more detailed
examples.
.. _Terraform Salt: https://github.com/dmacvicar/terraform-provider-salt
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals
import logging
import os.path
# Import Salt libs
import salt.utils.files
import salt.utils.json
log = logging.getLogger(__name__)
TF_OUTPUT_PREFIX = 'salt.roster.'
TF_ROSTER_ATTRS = {'host': 's',
'user': 's',
'passwd': 's',
'port': 'i',
'sudo': 'b',
'sudo_user': 's',
'tty': 'b', 'priv': 's',
'timeout': 'i',
'minion_opts': 'm',
'thin_dir': 's',
'cmd_umask': 'i'}
MINION_ID = 'salt_id'
def _handle_salt_host_resource(resource):
'''
Handles salt_host resources.
See https://github.com/dmacvicar/terraform-provider-salt
Returns roster attributes for the resource or None
'''
ret = {}
attrs = resource.get('primary', {}).get('attributes', {})
ret[MINION_ID] = attrs.get(MINION_ID)
valid_attrs = set(attrs.keys()).intersection(TF_ROSTER_ATTRS.keys())
for attr in valid_attrs:
ret[attr] = _cast_output_to_type(attrs.get(attr), TF_ROSTER_ATTRS.get(attr))
return ret
def _add_ssh_key(ret):
'''
Setups the salt-ssh minion to be accessed with salt-ssh default key
'''
priv = None
if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.expanduser('~/.ssh/id_rsa')
else:
priv = __opts__.get(
'ssh_priv',
os.path.abspath(os.path.join(
__opts__['pki_dir'],
'ssh',
'salt-ssh.rsa'
))
)
if priv and os.path.isfile(priv):
ret['priv'] = priv
def _cast_output_to_type(value, typ):
'''cast the value depending on the terraform type'''
if typ == 'b':
return bool(value)
if typ == 'i':
return int(value)
return value
def _parse_state_file(state_file_path='terraform.tfstate'):
'''
Parses the terraform state file passing different resource types to the right handler
'''
ret = {}
with salt.utils.files.fopen(state_file_path, 'r') as fh_:
tfstate = salt.utils.json.load(fh_)
modules = tfstate.get('modules')
if not modules:
log.error('Malformed tfstate file. No modules found')
return ret
for module in modules:
resources = module.get('resources', [])
for resource_name, resource in salt.ext.six.iteritems(resources):
roster_entry = None
if resource['type'] == 'salt_host':
roster_entry = _handle_salt_host_resource(resource)
if not roster_entry:
continue
minion_id = roster_entry.get(MINION_ID, resource.get('id'))
if not minion_id:
continue
if MINION_ID in roster_entry:
del roster_entry[MINION_ID]
_add_ssh_key(roster_entry)
ret[minion_id] = roster_entry
return ret
|
saltstack/salt
|
salt/states/win_powercfg.py
|
set_timeout
|
python
|
def set_timeout(name, value, power='ac', scheme=None):
'''
Set the sleep timeouts of specific items such as disk, monitor, etc.
Args:
name (str)
The setting to change, can be one of the following:
- ``monitor``
- ``disk``
- ``standby``
- ``hibernate``
value (int):
The amount of time in minutes before the item will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
CLI Example:
.. code-block:: yaml
# Set monitor timeout to 30 minutes on Battery
monitor:
powercfg.set_timeout:
- value: 30
- power: dc
# Set disk timeout to 10 minutes on AC Power
disk:
powercfg.set_timeout:
- value: 10
- power: ac
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
# Validate name values
name = name.lower()
if name not in ['monitor', 'disk', 'standby', 'hibernate']:
ret['result'] = False
ret['comment'] = '"{0}" is not a valid setting'.format(name)
log.debug(ret['comment'])
return ret
# Validate power values
power = power.lower()
if power not in ['ac', 'dc']:
ret['result'] = False
ret['comment'] = '"{0}" is not a power type'.format(power)
log.debug(ret['comment'])
return ret
# Get current settings
old = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme)
# Check current settings
if old[power] == value:
ret['comment'] = '{0} timeout on {1} power is already set to {2}' \
''.format(name.capitalize(), power.upper(), value)
return ret
else:
ret['comment'] = '{0} timeout on {1} power will be set to {2}' \
''.format(name.capitalize(), power.upper(), value)
# Check for test=True
if __opts__['test']:
ret['result'] = None
return ret
# Set the timeout value
__salt__['powercfg.set_{0}_timeout'.format(name)](
timeout=value,
power=power,
scheme=scheme)
# Get the setting after the change
new = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme)
changes = salt.utils.data.compare_dicts(old, new)
if changes:
ret['changes'] = {name: changes}
ret['comment'] = '{0} timeout on {1} power set to {2}' \
''.format(name.capitalize(), power.upper(), value)
log.debug(ret['comment'])
else:
ret['changes'] = {}
ret['comment'] = 'Failed to set {0} timeout on {1} power to {2}' \
''.format(name, power.upper(), value)
log.debug(ret['comment'])
ret['result'] = False
return ret
|
Set the sleep timeouts of specific items such as disk, monitor, etc.
Args:
name (str)
The setting to change, can be one of the following:
- ``monitor``
- ``disk``
- ``standby``
- ``hibernate``
value (int):
The amount of time in minutes before the item will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
CLI Example:
.. code-block:: yaml
# Set monitor timeout to 30 minutes on Battery
monitor:
powercfg.set_timeout:
- value: 30
- power: dc
# Set disk timeout to 10 minutes on AC Power
disk:
powercfg.set_timeout:
- value: 10
- power: ac
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_powercfg.py#L40-L150
| null |
# -*- coding: utf-8 -*-
'''
This module allows you to control the power settings of a windows minion via
powercfg.
.. versionadded:: 2015.8.0
.. code-block:: yaml
# Set timeout to 30 minutes on battery power
monitor:
powercfg.set_timeout:
- value: 30
- power: dc
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
# Import Salt Libs
import salt.utils.data
import salt.utils.platform
log = logging.getLogger(__name__)
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
|
saltstack/salt
|
salt/minion.py
|
resolve_dns
|
python
|
def resolve_dns(opts, fallback=True):
'''
Resolves the master_ip and master_uri options
'''
ret = {}
check_dns = True
if (opts.get('file_client', 'remote') == 'local' and
not opts.get('use_master_when_local', False)):
check_dns = False
# Since salt.log is imported below, salt.utils.network needs to be imported here as well
import salt.utils.network
if check_dns is True:
try:
if opts['master'] == '':
raise SaltSystemExit
ret['master_ip'] = salt.utils.network.dns_check(
opts['master'],
int(opts['master_port']),
True,
opts['ipv6'],
attempt_connect=False)
except SaltClientError:
retry_dns_count = opts.get('retry_dns_count', None)
if opts['retry_dns']:
while True:
if retry_dns_count is not None:
if retry_dns_count == 0:
raise SaltMasterUnresolvableError
retry_dns_count -= 1
import salt.log
msg = ('Master hostname: \'{0}\' not found or not responsive. '
'Retrying in {1} seconds').format(opts['master'], opts['retry_dns'])
if salt.log.setup.is_console_configured():
log.error(msg)
else:
print('WARNING: {0}'.format(msg))
time.sleep(opts['retry_dns'])
try:
ret['master_ip'] = salt.utils.network.dns_check(
opts['master'],
int(opts['master_port']),
True,
opts['ipv6'],
attempt_connect=False)
break
except SaltClientError:
pass
else:
if fallback:
ret['master_ip'] = '127.0.0.1'
else:
raise
except SaltSystemExit:
unknown_str = 'unknown address'
master = opts.get('master', unknown_str)
if master == '':
master = unknown_str
if opts.get('__role') == 'syndic':
err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \
'Set \'syndic_master\' value in minion config.'.format(master)
else:
err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \
'Set \'master\' value in minion config.'.format(master)
log.error(err)
raise SaltSystemExit(code=42, msg=err)
else:
ret['master_ip'] = '127.0.0.1'
if 'master_ip' in ret and 'master_ip' in opts:
if ret['master_ip'] != opts['master_ip']:
log.warning(
'Master ip address changed from %s to %s',
opts['master_ip'], ret['master_ip']
)
if opts['source_interface_name']:
log.trace('Custom source interface required: %s', opts['source_interface_name'])
interfaces = salt.utils.network.interfaces()
log.trace('The following interfaces are available on this Minion:')
log.trace(interfaces)
if opts['source_interface_name'] in interfaces:
if interfaces[opts['source_interface_name']]['up']:
addrs = interfaces[opts['source_interface_name']]['inet'] if not opts['ipv6'] else\
interfaces[opts['source_interface_name']]['inet6']
ret['source_ip'] = addrs[0]['address']
log.debug('Using %s as source IP address', ret['source_ip'])
else:
log.warning('The interface %s is down so it cannot be used as source to connect to the Master',
opts['source_interface_name'])
else:
log.warning('%s is not a valid interface. Ignoring.', opts['source_interface_name'])
elif opts['source_address']:
ret['source_ip'] = salt.utils.network.dns_check(
opts['source_address'],
int(opts['source_ret_port']),
True,
opts['ipv6'],
attempt_connect=False)
log.debug('Using %s as source IP address', ret['source_ip'])
if opts['source_ret_port']:
ret['source_ret_port'] = int(opts['source_ret_port'])
log.debug('Using %d as source port for the ret server', ret['source_ret_port'])
if opts['source_publish_port']:
ret['source_publish_port'] = int(opts['source_publish_port'])
log.debug('Using %d as source port for the master pub', ret['source_publish_port'])
ret['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=ret['master_ip'], port=opts['master_port'])
log.debug('Master URI: %s', ret['master_uri'])
return ret
|
Resolves the master_ip and master_uri options
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/minion.py#L133-L242
| null |
# -*- coding: utf-8 -*-
'''
Routines to set up a minion
'''
# Import python libs
from __future__ import absolute_import, print_function, with_statement, unicode_literals
import functools
import os
import sys
import copy
import time
import types
import signal
import random
import logging
import threading
import traceback
import contextlib
import multiprocessing
from random import randint, shuffle
from stat import S_IMODE
import salt.serializers.msgpack
from binascii import crc32
# Import Salt Libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt._compat import ipaddress
from salt.utils.network import parse_host_port
from salt.ext.six.moves import range
from salt.utils.zeromq import zmq, ZMQDefaultLoop, install_zmq, ZMQ_VERSION_INFO
import salt.transport.client
import salt.defaults.exitcodes
from salt.utils.ctx import RequestContext
# pylint: enable=no-name-in-module,redefined-builtin
import tornado
HAS_PSUTIL = False
try:
import salt.utils.psutil_compat as psutil
HAS_PSUTIL = True
except ImportError:
pass
HAS_RESOURCE = False
try:
import resource
HAS_RESOURCE = True
except ImportError:
pass
try:
import zmq.utils.monitor
HAS_ZMQ_MONITOR = True
except ImportError:
HAS_ZMQ_MONITOR = False
try:
import salt.utils.win_functions
HAS_WIN_FUNCTIONS = True
except ImportError:
HAS_WIN_FUNCTIONS = False
# pylint: enable=import-error
# Import salt libs
import salt
import salt.client
import salt.crypt
import salt.loader
import salt.beacons
import salt.engines
import salt.payload
import salt.pillar
import salt.syspaths
import salt.utils.args
import salt.utils.context
import salt.utils.data
import salt.utils.error
import salt.utils.event
import salt.utils.files
import salt.utils.jid
import salt.utils.minion
import salt.utils.minions
import salt.utils.network
import salt.utils.platform
import salt.utils.process
import salt.utils.schedule
import salt.utils.ssdp
import salt.utils.user
import salt.utils.zeromq
import salt.defaults.events
import salt.defaults.exitcodes
import salt.cli.daemons
import salt.log.setup
import salt.utils.dictupdate
from salt.config import DEFAULT_MINION_OPTS
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.utils.debug import enable_sigusr1_handler
from salt.utils.event import tagify
from salt.utils.odict import OrderedDict
from salt.utils.process import (default_signals,
SignalHandlingMultiprocessingProcess,
ProcessManager)
from salt.exceptions import (
CommandExecutionError,
CommandNotFoundError,
SaltInvocationError,
SaltReqTimeoutError,
SaltClientError,
SaltSystemExit,
SaltDaemonNotRunning,
SaltException,
SaltMasterUnresolvableError
)
import tornado.gen # pylint: disable=F0401
import tornado.ioloop # pylint: disable=F0401
log = logging.getLogger(__name__)
# To set up a minion:
# 1. Read in the configuration
# 2. Generate the function mapping dict
# 3. Authenticate with the master
# 4. Store the AES key
# 5. Connect to the publisher
# 6. Handle publications
def prep_ip_port(opts):
'''
parse host:port values from opts['master'] and return valid:
master: ip address or hostname as a string
master_port: (optional) master returner port as integer
e.g.:
- master: 'localhost:1234' -> {'master': 'localhost', 'master_port': 1234}
- master: '127.0.0.1:1234' -> {'master': '127.0.0.1', 'master_port' :1234}
- master: '[::1]:1234' -> {'master': '::1', 'master_port': 1234}
- master: 'fe80::a00:27ff:fedc:ba98' -> {'master': 'fe80::a00:27ff:fedc:ba98'}
'''
ret = {}
# Use given master IP if "ip_only" is set or if master_ip is an ipv6 address without
# a port specified. The is_ipv6 check returns False if brackets are used in the IP
# definition such as master: '[::1]:1234'.
if opts['master_uri_format'] == 'ip_only':
ret['master'] = ipaddress.ip_address(opts['master'])
else:
host, port = parse_host_port(opts['master'])
ret = {'master': host}
if port:
ret.update({'master_port': port})
return ret
def get_proc_dir(cachedir, **kwargs):
'''
Given the cache directory, return the directory that process data is
stored in, creating it if it doesn't exist.
The following optional Keyword Arguments are handled:
mode: which is anything os.makedir would accept as mode.
uid: the uid to set, if not set, or it is None or -1 no changes are
made. Same applies if the directory is already owned by this
uid. Must be int. Works only on unix/unix like systems.
gid: the gid to set, if not set, or it is None or -1 no changes are
made. Same applies if the directory is already owned by this
gid. Must be int. Works only on unix/unix like systems.
'''
fn_ = os.path.join(cachedir, 'proc')
mode = kwargs.pop('mode', None)
if mode is None:
mode = {}
else:
mode = {'mode': mode}
if not os.path.isdir(fn_):
# proc_dir is not present, create it with mode settings
os.makedirs(fn_, **mode)
d_stat = os.stat(fn_)
# if mode is not an empty dict then we have an explicit
# dir mode. So lets check if mode needs to be changed.
if mode:
mode_part = S_IMODE(d_stat.st_mode)
if mode_part != mode['mode']:
os.chmod(fn_, (d_stat.st_mode ^ mode_part) | mode['mode'])
if hasattr(os, 'chown'):
# only on unix/unix like systems
uid = kwargs.pop('uid', -1)
gid = kwargs.pop('gid', -1)
# if uid and gid are both -1 then go ahead with
# no changes at all
if (d_stat.st_uid != uid or d_stat.st_gid != gid) and \
[i for i in (uid, gid) if i != -1]:
os.chown(fn_, uid, gid)
return fn_
def load_args_and_kwargs(func, args, data=None, ignore_invalid=False):
'''
Detect the args and kwargs that need to be passed to a function call, and
check them against what was passed.
'''
argspec = salt.utils.args.get_function_argspec(func)
_args = []
_kwargs = {}
invalid_kwargs = []
for arg in args:
if isinstance(arg, dict) and arg.pop('__kwarg__', False) is True:
# if the arg is a dict with __kwarg__ == True, then its a kwarg
for key, val in six.iteritems(arg):
if argspec.keywords or key in argspec.args:
# Function supports **kwargs or is a positional argument to
# the function.
_kwargs[key] = val
else:
# **kwargs not in argspec and parsed argument name not in
# list of positional arguments. This keyword argument is
# invalid.
invalid_kwargs.append('{0}={1}'.format(key, val))
continue
else:
string_kwarg = salt.utils.args.parse_input([arg], condition=False)[1] # pylint: disable=W0632
if string_kwarg:
if argspec.keywords or next(six.iterkeys(string_kwarg)) in argspec.args:
# Function supports **kwargs or is a positional argument to
# the function.
_kwargs.update(string_kwarg)
else:
# **kwargs not in argspec and parsed argument name not in
# list of positional arguments. This keyword argument is
# invalid.
for key, val in six.iteritems(string_kwarg):
invalid_kwargs.append('{0}={1}'.format(key, val))
else:
_args.append(arg)
if invalid_kwargs and not ignore_invalid:
salt.utils.args.invalid_kwargs(invalid_kwargs)
if argspec.keywords and isinstance(data, dict):
# this function accepts **kwargs, pack in the publish data
for key, val in six.iteritems(data):
_kwargs['__pub_{0}'.format(key)] = val
return _args, _kwargs
def eval_master_func(opts):
'''
Evaluate master function if master type is 'func'
and save it result in opts['master']
'''
if '__master_func_evaluated' not in opts:
# split module and function and try loading the module
mod_fun = opts['master']
mod, fun = mod_fun.split('.')
try:
master_mod = salt.loader.raw_mod(opts, mod, fun)
if not master_mod:
raise KeyError
# we take whatever the module returns as master address
opts['master'] = master_mod[mod_fun]()
# Check for valid types
if not isinstance(opts['master'], (six.string_types, list)):
raise TypeError
opts['__master_func_evaluated'] = True
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except TypeError:
log.error('%s returned from %s is not a string', opts['master'], mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated master from module: %s', mod_fun)
def master_event(type, master=None):
'''
Centralized master event function which will return event type based on event_map
'''
event_map = {'connected': '__master_connected',
'disconnected': '__master_disconnected',
'failback': '__master_failback',
'alive': '__master_alive'}
if type == 'alive' and master is not None:
return '{0}_{1}'.format(event_map.get(type), master)
return event_map.get(type, None)
def service_name():
'''
Return the proper service name based on platform
'''
return 'salt_minion' if 'bsd' in sys.platform else 'salt-minion'
class MinionBase(object):
def __init__(self, opts):
self.opts = opts
@staticmethod
def process_schedule(minion, loop_interval):
try:
if hasattr(minion, 'schedule'):
minion.schedule.eval()
else:
log.error('Minion scheduler not initialized. Scheduled jobs will not be run.')
return
# Check if scheduler requires lower loop interval than
# the loop_interval setting
if minion.schedule.loop_interval < loop_interval:
loop_interval = minion.schedule.loop_interval
log.debug(
'Overriding loop_interval because of scheduled jobs.'
)
except Exception as exc:
log.error('Exception %s occurred in scheduled job', exc)
return loop_interval
def process_beacons(self, functions):
'''
Evaluate all of the configured beacons, grab the config again in case
the pillar or grains changed
'''
if 'config.merge' in functions:
b_conf = functions['config.merge']('beacons', self.opts['beacons'], omit_opts=True)
if b_conf:
return self.beacons.process(b_conf, self.opts['grains']) # pylint: disable=no-member
return []
@tornado.gen.coroutine
def eval_master(self,
opts,
timeout=60,
safe=True,
failed=False,
failback=False):
'''
Evaluates and returns a tuple of the current master address and the pub_channel.
In standard mode, just creates a pub_channel with the given master address.
With master_type=func evaluates the current master address from the given
module and then creates a pub_channel.
With master_type=failover takes the list of masters and loops through them.
The first one that allows the minion to create a pub_channel is then
returned. If this function is called outside the minions initialization
phase (for example from the minions main event-loop when a master connection
loss was detected), 'failed' should be set to True. The current
(possibly failed) master will then be removed from the list of masters.
'''
# return early if we are not connecting to a master
if opts['master_type'] == 'disable':
log.warning('Master is set to disable, skipping connection')
self.connected = False
raise tornado.gen.Return((None, None))
# Run masters discovery over SSDP. This may modify the whole configuration,
# depending of the networking and sets of masters.
# if we are using multimaster, discovery can only happen at start time
# because MinionManager handles it. by eval_master time the minion doesn't
# know about other siblings currently running
if isinstance(self.opts['discovery'], dict) and not self.opts['discovery'].get('multimaster'):
self._discover_masters()
# check if master_type was altered from its default
if opts['master_type'] != 'str' and opts['__role'] != 'syndic':
# check for a valid keyword
if opts['master_type'] == 'func':
eval_master_func(opts)
# if failover or distributed is set, master has to be of type list
elif opts['master_type'] in ('failover', 'distributed'):
if isinstance(opts['master'], list):
log.info(
'Got list of available master addresses: %s',
opts['master']
)
if opts['master_type'] == 'distributed':
master_len = len(opts['master'])
if master_len > 1:
secondary_masters = opts['master'][1:]
master_idx = crc32(opts['id']) % master_len
try:
preferred_masters = opts['master']
preferred_masters[0] = opts['master'][master_idx]
preferred_masters[1:] = [m for m in opts['master'] if m != preferred_masters[0]]
opts['master'] = preferred_masters
log.info('Distributed to the master at \'%s\'.', opts['master'][0])
except (KeyError, AttributeError, TypeError):
log.warning('Failed to distribute to a specific master.')
else:
log.warning('master_type = distributed needs more than 1 master.')
if opts['master_shuffle']:
log.warning(
'Use of \'master_shuffle\' detected. \'master_shuffle\' is deprecated in favor '
'of \'random_master\'. Please update your minion config file.'
)
opts['random_master'] = opts['master_shuffle']
opts['auth_tries'] = 0
if opts['master_failback'] and opts['master_failback_interval'] == 0:
opts['master_failback_interval'] = opts['master_alive_interval']
# if opts['master'] is a str and we have never created opts['master_list']
elif isinstance(opts['master'], six.string_types) and ('master_list' not in opts):
# We have a string, but a list was what was intended. Convert.
# See issue 23611 for details
opts['master'] = [opts['master']]
elif opts['__role'] == 'syndic':
log.info('Syndic setting master_syndic to \'%s\'', opts['master'])
# if failed=True, the minion was previously connected
# we're probably called from the minions main-event-loop
# because a master connection loss was detected. remove
# the possibly failed master from the list of masters.
elif failed:
if failback:
# failback list of masters to original config
opts['master'] = opts['master_list']
else:
log.info(
'Moving possibly failed master %s to the end of '
'the list of masters', opts['master']
)
if opts['master'] in opts['local_masters']:
# create new list of master with the possibly failed
# one moved to the end
failed_master = opts['master']
opts['master'] = [x for x in opts['local_masters'] if opts['master'] != x]
opts['master'].append(failed_master)
else:
opts['master'] = opts['master_list']
else:
msg = ('master_type set to \'failover\' but \'master\' '
'is not of type list but of type '
'{0}'.format(type(opts['master'])))
log.error(msg)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# If failover is set, minion have to failover on DNS errors instead of retry DNS resolve.
# See issue 21082 for details
if opts['retry_dns'] and opts['master_type'] == 'failover':
msg = ('\'master_type\' set to \'failover\' but \'retry_dns\' is not 0. '
'Setting \'retry_dns\' to 0 to failover to the next master on DNS errors.')
log.critical(msg)
opts['retry_dns'] = 0
else:
msg = ('Invalid keyword \'{0}\' for variable '
'\'master_type\''.format(opts['master_type']))
log.error(msg)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# FIXME: if SMinion don't define io_loop, it can't switch master see #29088
# Specify kwargs for the channel factory so that SMinion doesn't need to define an io_loop
# (The channel factories will set a default if the kwarg isn't passed)
factory_kwargs = {'timeout': timeout, 'safe': safe}
if getattr(self, 'io_loop', None):
factory_kwargs['io_loop'] = self.io_loop # pylint: disable=no-member
tries = opts.get('master_tries', 1)
attempts = 0
# if we have a list of masters, loop through them and be
# happy with the first one that allows us to connect
if isinstance(opts['master'], list):
conn = False
last_exc = None
opts['master_uri_list'] = []
opts['local_masters'] = copy.copy(opts['master'])
# shuffle the masters and then loop through them
if opts['random_master']:
# master_failback is only used when master_type is set to failover
if opts['master_type'] == 'failover' and opts['master_failback']:
secondary_masters = opts['local_masters'][1:]
shuffle(secondary_masters)
opts['local_masters'][1:] = secondary_masters
else:
shuffle(opts['local_masters'])
# This sits outside of the connection loop below because it needs to set
# up a list of master URIs regardless of which masters are available
# to connect _to_. This is primarily used for masterless mode, when
# we need a list of master URIs to fire calls back to.
for master in opts['local_masters']:
opts['master'] = master
opts.update(prep_ip_port(opts))
opts['master_uri_list'].append(resolve_dns(opts)['master_uri'])
while True:
if attempts != 0:
# Give up a little time between connection attempts
# to allow the IOLoop to run any other scheduled tasks.
yield tornado.gen.sleep(opts['acceptance_wait_time'])
attempts += 1
if tries > 0:
log.debug(
'Connecting to master. Attempt %s of %s',
attempts, tries
)
else:
log.debug(
'Connecting to master. Attempt %s (infinite attempts)',
attempts
)
for master in opts['local_masters']:
opts['master'] = master
opts.update(prep_ip_port(opts))
opts.update(resolve_dns(opts))
# on first run, update self.opts with the whole master list
# to enable a minion to re-use old masters if they get fixed
if 'master_list' not in opts:
opts['master_list'] = copy.copy(opts['local_masters'])
self.opts = opts
pub_channel = salt.transport.client.AsyncPubChannel.factory(opts, **factory_kwargs)
try:
yield pub_channel.connect()
conn = True
break
except SaltClientError as exc:
last_exc = exc
if exc.strerror.startswith('Could not access'):
msg = (
'Failed to initiate connection with Master '
'%s: check ownership/permissions. Error '
'message: %s', opts['master'], exc
)
else:
msg = ('Master %s could not be reached, trying next '
'next master (if any)', opts['master'])
log.info(msg)
continue
if not conn:
if attempts == tries:
# Exhausted all attempts. Return exception.
self.connected = False
self.opts['master'] = copy.copy(self.opts['local_masters'])
log.error(
'No master could be reached or all masters '
'denied the minion\'s connection attempt.'
)
# If the code reaches this point, 'last_exc'
# should already be set.
raise last_exc # pylint: disable=E0702
else:
self.tok = pub_channel.auth.gen_token(b'salt')
self.connected = True
raise tornado.gen.Return((opts['master'], pub_channel))
# single master sign in
else:
if opts['random_master']:
log.warning('random_master is True but there is only one master specified. Ignoring.')
while True:
if attempts != 0:
# Give up a little time between connection attempts
# to allow the IOLoop to run any other scheduled tasks.
yield tornado.gen.sleep(opts['acceptance_wait_time'])
attempts += 1
if tries > 0:
log.debug(
'Connecting to master. Attempt %s of %s',
attempts, tries
)
else:
log.debug(
'Connecting to master. Attempt %s (infinite attempts)',
attempts
)
opts.update(prep_ip_port(opts))
opts.update(resolve_dns(opts))
try:
if self.opts['transport'] == 'detect':
self.opts['detect_mode'] = True
for trans in ('zeromq', 'tcp'):
if trans == 'zeromq' and not zmq:
continue
self.opts['transport'] = trans
pub_channel = salt.transport.client.AsyncPubChannel.factory(self.opts, **factory_kwargs)
yield pub_channel.connect()
if not pub_channel.auth.authenticated:
continue
del self.opts['detect_mode']
break
else:
pub_channel = salt.transport.client.AsyncPubChannel.factory(self.opts, **factory_kwargs)
yield pub_channel.connect()
self.tok = pub_channel.auth.gen_token(b'salt')
self.connected = True
raise tornado.gen.Return((opts['master'], pub_channel))
except SaltClientError as exc:
if attempts == tries:
# Exhausted all attempts. Return exception.
self.connected = False
raise exc
def _discover_masters(self):
'''
Discover master(s) and decide where to connect, if SSDP is around.
This modifies the configuration on the fly.
:return:
'''
if self.opts['master'] == DEFAULT_MINION_OPTS['master'] and self.opts['discovery'] is not False:
master_discovery_client = salt.utils.ssdp.SSDPDiscoveryClient()
masters = {}
for att in range(self.opts['discovery'].get('attempts', 3)):
try:
att += 1
log.info('Attempting %s time(s) to discover masters', att)
masters.update(master_discovery_client.discover())
if not masters:
time.sleep(self.opts['discovery'].get('pause', 5))
else:
break
except Exception as err:
log.error('SSDP discovery failure: %s', err)
break
if masters:
policy = self.opts.get('discovery', {}).get('match', 'any')
if policy not in ['any', 'all']:
log.error('SSDP configuration matcher failure: unknown value "%s". '
'Should be "any" or "all"', policy)
return
mapping = self.opts['discovery'].get('mapping', {})
discovered = []
for addr, mappings in masters.items():
for proto_data in mappings:
cnt = len([key for key, value in mapping.items()
if proto_data.get('mapping', {}).get(key) == value])
if policy == 'any' and bool(cnt) or cnt == len(mapping):
if self.opts['discovery'].get('multimaster'):
discovered.append(proto_data['master'])
else:
self.opts['master'] = proto_data['master']
return
self.opts['master'] = discovered
def _return_retry_timer(self):
'''
Based on the minion configuration, either return a randomized timer or
just return the value of the return_retry_timer.
'''
msg = 'Minion return retry timer set to %s seconds'
if self.opts.get('return_retry_timer_max'):
try:
random_retry = randint(self.opts['return_retry_timer'], self.opts['return_retry_timer_max'])
retry_msg = msg % random_retry
log.debug('%s (randomized)', msg % random_retry)
return random_retry
except ValueError:
# Catch wiseguys using negative integers here
log.error(
'Invalid value (return_retry_timer: %s or '
'return_retry_timer_max: %s). Both must be positive '
'integers.',
self.opts['return_retry_timer'],
self.opts['return_retry_timer_max'],
)
log.debug(msg, DEFAULT_MINION_OPTS['return_retry_timer'])
return DEFAULT_MINION_OPTS['return_retry_timer']
else:
log.debug(msg, self.opts.get('return_retry_timer'))
return self.opts.get('return_retry_timer')
class SMinion(MinionBase):
'''
Create an object that has loaded all of the minion module functions,
grains, modules, returners etc. The SMinion allows developers to
generate all of the salt minion functions and present them with these
functions for general use.
'''
def __init__(self, opts):
# Late setup of the opts grains, so we can log from the grains module
import salt.loader
opts['grains'] = salt.loader.grains(opts)
super(SMinion, self).__init__(opts)
# run ssdp discovery if necessary
self._discover_masters()
# Clean out the proc directory (default /var/cache/salt/minion/proc)
if (self.opts.get('file_client', 'remote') == 'remote'
or self.opts.get('use_master_when_local', False)):
install_zmq()
io_loop = ZMQDefaultLoop.current()
io_loop.run_sync(
lambda: self.eval_master(self.opts, failed=True)
)
self.gen_modules(initial_load=True)
# If configured, cache pillar data on the minion
if self.opts['file_client'] == 'remote' and self.opts.get('minion_pillar_cache', False):
import salt.utils.yaml
pdir = os.path.join(self.opts['cachedir'], 'pillar')
if not os.path.isdir(pdir):
os.makedirs(pdir, 0o700)
ptop = os.path.join(pdir, 'top.sls')
if self.opts['saltenv'] is not None:
penv = self.opts['saltenv']
else:
penv = 'base'
cache_top = {penv: {self.opts['id']: ['cache']}}
with salt.utils.files.fopen(ptop, 'wb') as fp_:
salt.utils.yaml.safe_dump(cache_top, fp_)
os.chmod(ptop, 0o600)
cache_sls = os.path.join(pdir, 'cache.sls')
with salt.utils.files.fopen(cache_sls, 'wb') as fp_:
salt.utils.yaml.safe_dump(self.opts['pillar'], fp_)
os.chmod(cache_sls, 0o600)
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
'''
self.opts['pillar'] = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillarenv=self.opts.get('pillarenv'),
).compile_pillar()
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, utils=self.utils)
self.serializers = salt.loader.serializers(self.opts)
self.returners = salt.loader.returners(self.opts, self.functions)
self.proxy = salt.loader.proxy(self.opts, self.functions, self.returners, None)
# TODO: remove
self.function_errors = {} # Keep the funcs clean
self.states = salt.loader.states(self.opts,
self.functions,
self.utils,
self.serializers)
self.rend = salt.loader.render(self.opts, self.functions)
# self.matcher = Matcher(self.opts, self.functions)
self.matchers = salt.loader.matchers(self.opts)
self.functions['sys.reload_modules'] = self.gen_modules
self.executors = salt.loader.executors(self.opts)
class MasterMinion(object):
'''
Create a fully loaded minion function object for generic use on the
master. What makes this class different is that the pillar is
omitted, otherwise everything else is loaded cleanly.
'''
def __init__(
self,
opts,
returners=True,
states=True,
rend=True,
matcher=True,
whitelist=None,
ignore_config_errors=True):
self.opts = salt.config.minion_config(
opts['conf_file'],
ignore_config_errors=ignore_config_errors,
role='master'
)
self.opts.update(opts)
self.whitelist = whitelist
self.opts['grains'] = salt.loader.grains(opts)
self.opts['pillar'] = {}
self.mk_returners = returners
self.mk_states = states
self.mk_rend = rend
self.mk_matcher = matcher
self.gen_modules(initial_load=True)
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
'''
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(
self.opts,
utils=self.utils,
whitelist=self.whitelist,
initial_load=initial_load)
self.serializers = salt.loader.serializers(self.opts)
if self.mk_returners:
self.returners = salt.loader.returners(self.opts, self.functions)
if self.mk_states:
self.states = salt.loader.states(self.opts,
self.functions,
self.utils,
self.serializers)
if self.mk_rend:
self.rend = salt.loader.render(self.opts, self.functions)
if self.mk_matcher:
self.matchers = salt.loader.matchers(self.opts)
self.functions['sys.reload_modules'] = self.gen_modules
class MinionManager(MinionBase):
'''
Create a multi minion interface, this creates as many minions as are
defined in the master option and binds each minion object to a respective
master.
'''
def __init__(self, opts):
super(MinionManager, self).__init__(opts)
self.auth_wait = self.opts['acceptance_wait_time']
self.max_auth_wait = self.opts['acceptance_wait_time_max']
self.minions = []
self.jid_queue = []
install_zmq()
self.io_loop = ZMQDefaultLoop.current()
self.process_manager = ProcessManager(name='MultiMinionProcessManager')
self.io_loop.spawn_callback(self.process_manager.run, **{'asynchronous': True}) # Tornado backward compat
def __del__(self):
self.destroy()
def _bind(self):
# start up the event publisher, so we can see events during startup
self.event_publisher = salt.utils.event.AsyncEventPublisher(
self.opts,
io_loop=self.io_loop,
)
self.event = salt.utils.event.get_event('minion', opts=self.opts, io_loop=self.io_loop)
self.event.subscribe('')
self.event.set_event_handler(self.handle_event)
@tornado.gen.coroutine
def handle_event(self, package):
yield [minion.handle_event(package) for minion in self.minions]
def _create_minion_object(self, opts, timeout, safe,
io_loop=None, loaded_base_name=None,
jid_queue=None):
'''
Helper function to return the correct type of object
'''
return Minion(opts,
timeout,
safe,
io_loop=io_loop,
loaded_base_name=loaded_base_name,
jid_queue=jid_queue)
def _check_minions(self):
'''
Check the size of self.minions and raise an error if it's empty
'''
if not self.minions:
err = ('Minion unable to successfully connect to '
'a Salt Master.')
log.error(err)
def _spawn_minions(self, timeout=60):
'''
Spawn all the coroutines which will sign in to masters
'''
# Run masters discovery over SSDP. This may modify the whole configuration,
# depending of the networking and sets of masters. If match is 'any' we let
# eval_master handle the discovery instead so disconnections can also handle
# discovery
if isinstance(self.opts['discovery'], dict) and self.opts['discovery'].get('multimaster'):
self._discover_masters()
masters = self.opts['master']
if (self.opts['master_type'] in ('failover', 'distributed')) or not isinstance(self.opts['master'], list):
masters = [masters]
for master in masters:
s_opts = copy.deepcopy(self.opts)
s_opts['master'] = master
s_opts['multimaster'] = True
minion = self._create_minion_object(s_opts,
s_opts['auth_timeout'],
False,
io_loop=self.io_loop,
loaded_base_name='salt.loader.{0}'.format(s_opts['master']),
jid_queue=self.jid_queue)
self.io_loop.spawn_callback(self._connect_minion, minion)
self.io_loop.call_later(timeout, self._check_minions)
@tornado.gen.coroutine
def _connect_minion(self, minion):
'''
Create a minion, and asynchronously connect it to a master
'''
auth_wait = minion.opts['acceptance_wait_time']
failed = False
while True:
if failed:
if auth_wait < self.max_auth_wait:
auth_wait += self.auth_wait
log.debug(
"sleeping before reconnect attempt to %s [%d/%d]",
minion.opts['master'],
auth_wait,
self.max_auth_wait,
)
yield tornado.gen.sleep(auth_wait) # TODO: log?
try:
if minion.opts.get('beacons_before_connect', False):
minion.setup_beacons(before_connect=True)
if minion.opts.get('scheduler_before_connect', False):
minion.setup_scheduler(before_connect=True)
yield minion.connect_master(failed=failed)
minion.tune_in(start=False)
self.minions.append(minion)
break
except SaltClientError as exc:
failed = True
log.error(
'Error while bringing up minion for multi-master. Is '
'master at %s responding?', minion.opts['master']
)
except SaltMasterUnresolvableError:
err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \
'Set \'master\' value in minion config.'.format(minion.opts['master'])
log.error(err)
break
except Exception as e:
failed = True
log.critical(
'Unexpected error while connecting to %s',
minion.opts['master'], exc_info=True
)
# Multi Master Tune In
def tune_in(self):
'''
Bind to the masters
This loop will attempt to create connections to masters it hasn't connected
to yet, but once the initial connection is made it is up to ZMQ to do the
reconnect (don't know of an API to get the state here in salt)
'''
self._bind()
# Fire off all the minion coroutines
self._spawn_minions()
# serve forever!
self.io_loop.start()
@property
def restart(self):
for minion in self.minions:
if minion.restart:
return True
return False
def stop(self, signum):
for minion in self.minions:
minion.process_manager.stop_restarting()
minion.process_manager.send_signal_to_processes(signum)
# kill any remaining processes
minion.process_manager.kill_children()
minion.destroy()
def destroy(self):
for minion in self.minions:
minion.destroy()
class Minion(MinionBase):
'''
This class instantiates a minion, runs connections for a minion,
and loads all of the functions into the minion
'''
def __init__(self, opts, timeout=60, safe=True, loaded_base_name=None, io_loop=None, jid_queue=None): # pylint: disable=W0231
'''
Pass in the options dict
'''
# this means that the parent class doesn't know *which* master we connect to
super(Minion, self).__init__(opts)
self.timeout = timeout
self.safe = safe
self._running = None
self.win_proc = []
self.loaded_base_name = loaded_base_name
self.connected = False
self.restart = False
# Flag meaning minion has finished initialization including first connect to the master.
# True means the Minion is fully functional and ready to handle events.
self.ready = False
self.jid_queue = [] if jid_queue is None else jid_queue
self.periodic_callbacks = {}
if io_loop is None:
install_zmq()
self.io_loop = ZMQDefaultLoop.current()
else:
self.io_loop = io_loop
# Warn if ZMQ < 3.2
if zmq:
if ZMQ_VERSION_INFO < (3, 2):
log.warning(
'You have a version of ZMQ less than ZMQ 3.2! There are '
'known connection keep-alive issues with ZMQ < 3.2 which '
'may result in loss of contact with minions. Please '
'upgrade your ZMQ!'
)
# Late setup of the opts grains, so we can log from the grains
# module. If this is a proxy, however, we need to init the proxymodule
# before we can get the grains. We do this for proxies in the
# post_master_init
if not salt.utils.platform.is_proxy():
self.opts['grains'] = salt.loader.grains(opts)
else:
if self.opts.get('beacons_before_connect', False):
log.warning(
'\'beacons_before_connect\' is not supported '
'for proxy minions. Setting to False'
)
self.opts['beacons_before_connect'] = False
if self.opts.get('scheduler_before_connect', False):
log.warning(
'\'scheduler_before_connect\' is not supported '
'for proxy minions. Setting to False'
)
self.opts['scheduler_before_connect'] = False
log.info('Creating minion process manager')
if self.opts['random_startup_delay']:
sleep_time = random.randint(0, self.opts['random_startup_delay'])
log.info(
'Minion sleeping for %s seconds due to configured '
'startup_delay between 0 and %s seconds',
sleep_time, self.opts['random_startup_delay']
)
time.sleep(sleep_time)
self.process_manager = ProcessManager(name='MinionProcessManager')
self.io_loop.spawn_callback(self.process_manager.run, **{'asynchronous': True})
# We don't have the proxy setup yet, so we can't start engines
# Engines need to be able to access __proxy__
if not salt.utils.platform.is_proxy():
self.io_loop.spawn_callback(salt.engines.start_engines, self.opts,
self.process_manager)
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, self._handle_signals)
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGTERM, self._handle_signals)
def _handle_signals(self, signum, sigframe): # pylint: disable=unused-argument
self._running = False
# escalate the signals to the process manager
self.process_manager.stop_restarting()
self.process_manager.send_signal_to_processes(signum)
# kill any remaining processes
self.process_manager.kill_children()
time.sleep(1)
sys.exit(0)
def sync_connect_master(self, timeout=None, failed=False):
'''
Block until we are connected to a master
'''
self._sync_connect_master_success = False
log.debug("sync_connect_master")
def on_connect_master_future_done(future):
self._sync_connect_master_success = True
self.io_loop.stop()
self._connect_master_future = self.connect_master(failed=failed)
# finish connecting to master
self._connect_master_future.add_done_callback(on_connect_master_future_done)
if timeout:
self.io_loop.call_later(timeout, self.io_loop.stop)
try:
self.io_loop.start()
except KeyboardInterrupt:
self.destroy()
# I made the following 3 line oddity to preserve traceback.
# Please read PR #23978 before changing, hopefully avoiding regressions.
# Good luck, we're all counting on you. Thanks.
if self._connect_master_future.done():
future_exception = self._connect_master_future.exception()
if future_exception:
# This needs to be re-raised to preserve restart_on_error behavior.
raise six.reraise(*future_exception)
if timeout and self._sync_connect_master_success is False:
raise SaltDaemonNotRunning('Failed to connect to the salt-master')
@tornado.gen.coroutine
def connect_master(self, failed=False):
'''
Return a future which will complete when you are connected to a master
'''
master, self.pub_channel = yield self.eval_master(self.opts, self.timeout, self.safe, failed)
yield self._post_master_init(master)
# TODO: better name...
@tornado.gen.coroutine
def _post_master_init(self, master):
'''
Function to finish init after connecting to a master
This is primarily loading modules, pillars, etc. (since they need
to know which master they connected to)
If this function is changed, please check ProxyMinion._post_master_init
to see if those changes need to be propagated.
Minions and ProxyMinions need significantly different post master setups,
which is why the differences are not factored out into separate helper
functions.
'''
if self.connected:
self.opts['master'] = master
# Initialize pillar before loader to make pillar accessible in modules
async_pillar = salt.pillar.get_async_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillarenv=self.opts.get('pillarenv')
)
self.opts['pillar'] = yield async_pillar.compile_pillar()
async_pillar.destroy()
if not self.ready:
self._setup_core()
elif self.connected and self.opts['pillar']:
# The pillar has changed due to the connection to the master.
# Reload the functions so that they can use the new pillar data.
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
if hasattr(self, 'schedule'):
self.schedule.functions = self.functions
self.schedule.returners = self.returners
if not hasattr(self, 'schedule'):
self.schedule = salt.utils.schedule.Schedule(
self.opts,
self.functions,
self.returners,
cleanup=[master_event(type='alive')])
# add default scheduling jobs to the minions scheduler
if self.opts['mine_enabled'] and 'mine.update' in self.functions:
self.schedule.add_job({
'__mine_interval':
{
'function': 'mine.update',
'minutes': self.opts['mine_interval'],
'jid_include': True,
'maxrunning': 2,
'run_on_start': True,
'return_job': self.opts.get('mine_return_job', False)
}
}, persist=True)
log.info('Added mine.update to scheduler')
else:
self.schedule.delete_job('__mine_interval', persist=True)
# add master_alive job if enabled
if (self.opts['transport'] != 'tcp' and
self.opts['master_alive_interval'] > 0 and
self.connected):
self.schedule.add_job({
master_event(type='alive', master=self.opts['master']):
{
'function': 'status.master',
'seconds': self.opts['master_alive_interval'],
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master'],
'connected': True}
}
}, persist=True)
if self.opts['master_failback'] and \
'master_list' in self.opts and \
self.opts['master'] != self.opts['master_list'][0]:
self.schedule.add_job({
master_event(type='failback'):
{
'function': 'status.ping_master',
'seconds': self.opts['master_failback_interval'],
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master_list'][0]}
}
}, persist=True)
else:
self.schedule.delete_job(master_event(type='failback'), persist=True)
else:
self.schedule.delete_job(master_event(type='alive', master=self.opts['master']), persist=True)
self.schedule.delete_job(master_event(type='failback'), persist=True)
def _prep_mod_opts(self):
'''
Returns a copy of the opts with key bits stripped out
'''
mod_opts = {}
for key, val in six.iteritems(self.opts):
if key == 'logger':
continue
mod_opts[key] = val
return mod_opts
def _load_modules(self, force_refresh=False, notify=False, grains=None, opts=None):
'''
Return the functions and the returners loaded up from the loader
module
'''
opt_in = True
if not opts:
opts = self.opts
opt_in = False
# if this is a *nix system AND modules_max_memory is set, lets enforce
# a memory limit on module imports
# this feature ONLY works on *nix like OSs (resource module doesn't work on windows)
modules_max_memory = False
if opts.get('modules_max_memory', -1) > 0 and HAS_PSUTIL and HAS_RESOURCE:
log.debug(
'modules_max_memory set, enforcing a maximum of %s',
opts['modules_max_memory']
)
modules_max_memory = True
old_mem_limit = resource.getrlimit(resource.RLIMIT_AS)
rss, vms = psutil.Process(os.getpid()).memory_info()[:2]
mem_limit = rss + vms + opts['modules_max_memory']
resource.setrlimit(resource.RLIMIT_AS, (mem_limit, mem_limit))
elif opts.get('modules_max_memory', -1) > 0:
if not HAS_PSUTIL:
log.error('Unable to enforce modules_max_memory because psutil is missing')
if not HAS_RESOURCE:
log.error('Unable to enforce modules_max_memory because resource is missing')
# This might be a proxy minion
if hasattr(self, 'proxy'):
proxy = self.proxy
else:
proxy = None
if grains is None:
opts['grains'] = salt.loader.grains(opts, force_refresh, proxy=proxy)
self.utils = salt.loader.utils(opts, proxy=proxy)
if opts.get('multimaster', False):
s_opts = copy.deepcopy(opts)
functions = salt.loader.minion_mods(s_opts, utils=self.utils, proxy=proxy,
loaded_base_name=self.loaded_base_name, notify=notify)
else:
functions = salt.loader.minion_mods(opts, utils=self.utils, notify=notify, proxy=proxy)
returners = salt.loader.returners(opts, functions, proxy=proxy)
errors = {}
if '_errors' in functions:
errors = functions['_errors']
functions.pop('_errors')
# we're done, reset the limits!
if modules_max_memory is True:
resource.setrlimit(resource.RLIMIT_AS, old_mem_limit)
executors = salt.loader.executors(opts, functions, proxy=proxy)
if opt_in:
self.opts = opts
return functions, returners, errors, executors
def _send_req_sync(self, load, timeout):
if self.opts['minion_sign_messages']:
log.trace('Signing event to be published onto the bus.')
minion_privkey_path = os.path.join(self.opts['pki_dir'], 'minion.pem')
sig = salt.crypt.sign_message(minion_privkey_path, salt.serializers.msgpack.serialize(load))
load['sig'] = sig
channel = salt.transport.client.ReqChannel.factory(self.opts)
try:
return channel.send(load, timeout=timeout)
finally:
channel.close()
@tornado.gen.coroutine
def _send_req_async(self, load, timeout):
if self.opts['minion_sign_messages']:
log.trace('Signing event to be published onto the bus.')
minion_privkey_path = os.path.join(self.opts['pki_dir'], 'minion.pem')
sig = salt.crypt.sign_message(minion_privkey_path, salt.serializers.msgpack.serialize(load))
load['sig'] = sig
channel = salt.transport.client.AsyncReqChannel.factory(self.opts)
try:
ret = yield channel.send(load, timeout=timeout)
raise tornado.gen.Return(ret)
finally:
channel.close()
def _fire_master(self, data=None, tag=None, events=None, pretag=None, timeout=60, sync=True, timeout_handler=None):
'''
Fire an event on the master, or drop message if unable to send.
'''
load = {'id': self.opts['id'],
'cmd': '_minion_event',
'pretag': pretag,
'tok': self.tok}
if events:
load['events'] = events
elif data and tag:
load['data'] = data
load['tag'] = tag
elif not data and tag:
load['data'] = {}
load['tag'] = tag
else:
return
if sync:
try:
self._send_req_sync(load, timeout)
except salt.exceptions.SaltReqTimeoutError:
log.info('fire_master failed: master could not be contacted. Request timed out.')
# very likely one of the masters is dead, status.master will flush it
self.functions['status.master'](self.opts['master'])
return False
except Exception:
log.info('fire_master failed: %s', traceback.format_exc())
return False
else:
if timeout_handler is None:
def handle_timeout(*_):
log.info('fire_master failed: master could not be contacted. Request timed out.')
# very likely one of the masters is dead, status.master will flush it
self.functions['status.master'](self.opts['master'])
return True
timeout_handler = handle_timeout
with tornado.stack_context.ExceptionStackContext(timeout_handler):
self._send_req_async(load, timeout, callback=lambda f: None) # pylint: disable=unexpected-keyword-arg
return True
@tornado.gen.coroutine
def _handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
# Ensure payload is unicode. Disregard failure to decode binary blobs.
if six.PY2:
data = salt.utils.data.decode(data, keep=True)
if 'user' in data:
log.info(
'User %s Executing command %s with jid %s',
data['user'], data['fun'], data['jid']
)
else:
log.info(
'Executing command %s with jid %s',
data['fun'], data['jid']
)
log.debug('Command details %s', data)
# Don't duplicate jobs
log.trace('Started JIDs: %s', self.jid_queue)
if self.jid_queue is not None:
if data['jid'] in self.jid_queue:
return
else:
self.jid_queue.append(data['jid'])
if len(self.jid_queue) > self.opts['minion_jid_queue_hwm']:
self.jid_queue.pop(0)
if isinstance(data['fun'], six.string_types):
if data['fun'] == 'sys.reload_modules':
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
self.schedule.functions = self.functions
self.schedule.returners = self.returners
process_count_max = self.opts.get('process_count_max')
process_count_max_sleep_secs = self.opts.get('process_count_max_sleep_secs')
if process_count_max > 0:
process_count = len(salt.utils.minion.running(self.opts))
while process_count >= process_count_max:
log.warning('Maximum number of processes (%s) reached while '
'executing jid %s, waiting %s seconds...',
process_count_max,
data['jid'],
process_count_max_sleep_secs)
yield tornado.gen.sleep(process_count_max_sleep_secs)
process_count = len(salt.utils.minion.running(self.opts))
# We stash an instance references to allow for the socket
# communication in Windows. You can't pickle functions, and thus
# python needs to be able to reconstruct the reference on the other
# side.
instance = self
multiprocessing_enabled = self.opts.get('multiprocessing', True)
if multiprocessing_enabled:
if sys.platform.startswith('win'):
# let python reconstruct the minion on the other side if we're
# running on windows
instance = None
with default_signals(signal.SIGINT, signal.SIGTERM):
process = SignalHandlingMultiprocessingProcess(
target=self._target, args=(instance, self.opts, data, self.connected)
)
else:
process = threading.Thread(
target=self._target,
args=(instance, self.opts, data, self.connected),
name=data['jid']
)
if multiprocessing_enabled:
with default_signals(signal.SIGINT, signal.SIGTERM):
# Reset current signals before starting the process in
# order not to inherit the current signal handlers
process.start()
else:
process.start()
# TODO: remove the windows specific check?
if multiprocessing_enabled and not salt.utils.platform.is_windows():
# we only want to join() immediately if we are daemonizing a process
process.join()
elif salt.utils.platform.is_windows():
self.win_proc.append(process)
def ctx(self):
'''
Return a single context manager for the minion's data
'''
if six.PY2:
return contextlib.nested(
self.functions.context_dict.clone(),
self.returners.context_dict.clone(),
self.executors.context_dict.clone(),
)
else:
exitstack = contextlib.ExitStack()
exitstack.enter_context(self.functions.context_dict.clone())
exitstack.enter_context(self.returners.context_dict.clone())
exitstack.enter_context(self.executors.context_dict.clone())
return exitstack
@classmethod
def _target(cls, minion_instance, opts, data, connected):
if not minion_instance:
minion_instance = cls(opts)
minion_instance.connected = connected
if not hasattr(minion_instance, 'functions'):
functions, returners, function_errors, executors = (
minion_instance._load_modules(grains=opts['grains'])
)
minion_instance.functions = functions
minion_instance.returners = returners
minion_instance.function_errors = function_errors
minion_instance.executors = executors
if not hasattr(minion_instance, 'serial'):
minion_instance.serial = salt.payload.Serial(opts)
if not hasattr(minion_instance, 'proc_dir'):
uid = salt.utils.user.get_uid(user=opts.get('user', None))
minion_instance.proc_dir = (
get_proc_dir(opts['cachedir'], uid=uid)
)
def run_func(minion_instance, opts, data):
if isinstance(data['fun'], tuple) or isinstance(data['fun'], list):
return Minion._thread_multi_return(minion_instance, opts, data)
else:
return Minion._thread_return(minion_instance, opts, data)
with tornado.stack_context.StackContext(functools.partial(RequestContext,
{'data': data, 'opts': opts})):
with tornado.stack_context.StackContext(minion_instance.ctx):
run_func(minion_instance, opts, data)
@classmethod
def _thread_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
fn_ = os.path.join(minion_instance.proc_dir, data['jid'])
if opts['multiprocessing'] and not salt.utils.platform.is_windows():
# Shutdown the multiprocessing before daemonizing
salt.log.setup.shutdown_multiprocessing_logging()
salt.utils.process.daemonize_if(opts)
# Reconfigure multiprocessing logging after daemonizing
salt.log.setup.setup_multiprocessing_logging()
salt.utils.process.appendproctitle('{0}._thread_return {1}'.format(cls.__name__, data['jid']))
sdata = {'pid': os.getpid()}
sdata.update(data)
log.info('Starting a new job %s with PID %s', data['jid'], sdata['pid'])
with salt.utils.files.fopen(fn_, 'w+b') as fp_:
fp_.write(minion_instance.serial.dumps(sdata))
ret = {'success': False}
function_name = data['fun']
executors = data.get('module_executors') or \
getattr(minion_instance, 'module_executors', []) or \
opts.get('module_executors', ['direct_call'])
allow_missing_funcs = any([
minion_instance.executors['{0}.allow_missing_func'.format(executor)](function_name)
for executor in executors
if '{0}.allow_missing_func' in minion_instance.executors
])
if function_name in minion_instance.functions or allow_missing_funcs is True:
try:
minion_blackout_violation = False
if minion_instance.connected and minion_instance.opts['pillar'].get('minion_blackout', False):
whitelist = minion_instance.opts['pillar'].get('minion_blackout_whitelist', [])
# this minion is blacked out. Only allow saltutil.refresh_pillar and the whitelist
if function_name != 'saltutil.refresh_pillar' and function_name not in whitelist:
minion_blackout_violation = True
# use minion_blackout_whitelist from grains if it exists
if minion_instance.opts['grains'].get('minion_blackout', False):
whitelist = minion_instance.opts['grains'].get('minion_blackout_whitelist', [])
if function_name != 'saltutil.refresh_pillar' and function_name not in whitelist:
minion_blackout_violation = True
if minion_blackout_violation:
raise SaltInvocationError('Minion in blackout mode. Set \'minion_blackout\' '
'to False in pillar or grains to resume operations. Only '
'saltutil.refresh_pillar allowed in blackout mode.')
if function_name in minion_instance.functions:
func = minion_instance.functions[function_name]
args, kwargs = load_args_and_kwargs(
func,
data['arg'],
data)
else:
# only run if function_name is not in minion_instance.functions and allow_missing_funcs is True
func = function_name
args, kwargs = data['arg'], data
minion_instance.functions.pack['__context__']['retcode'] = 0
if isinstance(executors, six.string_types):
executors = [executors]
elif not isinstance(executors, list) or not executors:
raise SaltInvocationError("Wrong executors specification: {0}. String or non-empty list expected".
format(executors))
if opts.get('sudo_user', '') and executors[-1] != 'sudo':
executors[-1] = 'sudo' # replace the last one with sudo
log.trace('Executors list %s', executors) # pylint: disable=no-member
for name in executors:
fname = '{0}.execute'.format(name)
if fname not in minion_instance.executors:
raise SaltInvocationError("Executor '{0}' is not available".format(name))
return_data = minion_instance.executors[fname](opts, data, func, args, kwargs)
if return_data is not None:
break
if isinstance(return_data, types.GeneratorType):
ind = 0
iret = {}
for single in return_data:
if isinstance(single, dict) and isinstance(iret, dict):
iret.update(single)
else:
if not iret:
iret = []
iret.append(single)
tag = tagify([data['jid'], 'prog', opts['id'], six.text_type(ind)], 'job')
event_data = {'return': single}
minion_instance._fire_master(event_data, tag)
ind += 1
ret['return'] = iret
else:
ret['return'] = return_data
retcode = minion_instance.functions.pack['__context__'].get(
'retcode',
salt.defaults.exitcodes.EX_OK
)
if retcode == salt.defaults.exitcodes.EX_OK:
# No nonzero retcode in __context__ dunder. Check if return
# is a dictionary with a "result" or "success" key.
try:
func_result = all(return_data.get(x, True)
for x in ('result', 'success'))
except Exception:
# return data is not a dict
func_result = True
if not func_result:
retcode = salt.defaults.exitcodes.EX_GENERIC
ret['retcode'] = retcode
ret['success'] = retcode == salt.defaults.exitcodes.EX_OK
except CommandNotFoundError as exc:
msg = 'Command required for \'{0}\' not found'.format(
function_name
)
log.debug(msg, exc_info=True)
ret['return'] = '{0}: {1}'.format(msg, exc)
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
except CommandExecutionError as exc:
log.error(
'A command in \'%s\' had a problem: %s',
function_name, exc,
exc_info_on_loglevel=logging.DEBUG
)
ret['return'] = 'ERROR: {0}'.format(exc)
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
except SaltInvocationError as exc:
log.error(
'Problem executing \'%s\': %s',
function_name, exc,
exc_info_on_loglevel=logging.DEBUG
)
ret['return'] = 'ERROR executing \'{0}\': {1}'.format(
function_name, exc
)
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
except TypeError as exc:
msg = 'Passed invalid arguments to {0}: {1}\n{2}'.format(
function_name, exc, func.__doc__ or ''
)
log.warning(msg, exc_info_on_loglevel=logging.DEBUG)
ret['return'] = msg
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
except Exception:
msg = 'The minion function caused an exception'
log.warning(msg, exc_info_on_loglevel=True)
salt.utils.error.fire_exception(salt.exceptions.MinionError(msg), opts, job=data)
ret['return'] = '{0}: {1}'.format(msg, traceback.format_exc())
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
else:
docs = minion_instance.functions['sys.doc']('{0}*'.format(function_name))
if docs:
docs[function_name] = minion_instance.functions.missing_fun_string(function_name)
ret['return'] = docs
else:
ret['return'] = minion_instance.functions.missing_fun_string(function_name)
mod_name = function_name.split('.')[0]
if mod_name in minion_instance.function_errors:
ret['return'] += ' Possible reasons: \'{0}\''.format(
minion_instance.function_errors[mod_name]
)
ret['success'] = False
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
ret['out'] = 'nested'
ret['jid'] = data['jid']
ret['fun'] = data['fun']
ret['fun_args'] = data['arg']
if 'master_id' in data:
ret['master_id'] = data['master_id']
if 'metadata' in data:
if isinstance(data['metadata'], dict):
ret['metadata'] = data['metadata']
else:
log.warning('The metadata parameter must be a dictionary. Ignoring.')
if minion_instance.connected:
minion_instance._return_pub(
ret,
timeout=minion_instance._return_retry_timer()
)
# Add default returners from minion config
# Should have been coverted to comma-delimited string already
if isinstance(opts.get('return'), six.string_types):
if data['ret']:
data['ret'] = ','.join((data['ret'], opts['return']))
else:
data['ret'] = opts['return']
log.debug('minion return: %s', ret)
# TODO: make a list? Seems odd to split it this late :/
if data['ret'] and isinstance(data['ret'], six.string_types):
if 'ret_config' in data:
ret['ret_config'] = data['ret_config']
if 'ret_kwargs' in data:
ret['ret_kwargs'] = data['ret_kwargs']
ret['id'] = opts['id']
for returner in set(data['ret'].split(',')):
try:
returner_str = '{0}.returner'.format(returner)
if returner_str in minion_instance.returners:
minion_instance.returners[returner_str](ret)
else:
returner_err = minion_instance.returners.missing_fun_string(returner_str)
log.error(
'Returner %s could not be loaded: %s',
returner_str, returner_err
)
except Exception as exc:
log.exception(
'The return failed for job %s: %s', data['jid'], exc
)
@classmethod
def _thread_multi_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
fn_ = os.path.join(minion_instance.proc_dir, data['jid'])
if opts['multiprocessing'] and not salt.utils.platform.is_windows():
# Shutdown the multiprocessing before daemonizing
salt.log.setup.shutdown_multiprocessing_logging()
salt.utils.process.daemonize_if(opts)
# Reconfigure multiprocessing logging after daemonizing
salt.log.setup.setup_multiprocessing_logging()
salt.utils.process.appendproctitle('{0}._thread_multi_return {1}'.format(cls.__name__, data['jid']))
sdata = {'pid': os.getpid()}
sdata.update(data)
log.info('Starting a new job with PID %s', sdata['pid'])
with salt.utils.files.fopen(fn_, 'w+b') as fp_:
fp_.write(minion_instance.serial.dumps(sdata))
multifunc_ordered = opts.get('multifunc_ordered', False)
num_funcs = len(data['fun'])
if multifunc_ordered:
ret = {
'return': [None] * num_funcs,
'retcode': [None] * num_funcs,
'success': [False] * num_funcs
}
else:
ret = {
'return': {},
'retcode': {},
'success': {}
}
for ind in range(0, num_funcs):
if not multifunc_ordered:
ret['success'][data['fun'][ind]] = False
try:
minion_blackout_violation = False
if minion_instance.connected and minion_instance.opts['pillar'].get('minion_blackout', False):
whitelist = minion_instance.opts['pillar'].get('minion_blackout_whitelist', [])
# this minion is blacked out. Only allow saltutil.refresh_pillar and the whitelist
if data['fun'][ind] != 'saltutil.refresh_pillar' and data['fun'][ind] not in whitelist:
minion_blackout_violation = True
elif minion_instance.opts['grains'].get('minion_blackout', False):
whitelist = minion_instance.opts['grains'].get('minion_blackout_whitelist', [])
if data['fun'][ind] != 'saltutil.refresh_pillar' and data['fun'][ind] not in whitelist:
minion_blackout_violation = True
if minion_blackout_violation:
raise SaltInvocationError('Minion in blackout mode. Set \'minion_blackout\' '
'to False in pillar or grains to resume operations. Only '
'saltutil.refresh_pillar allowed in blackout mode.')
func = minion_instance.functions[data['fun'][ind]]
args, kwargs = load_args_and_kwargs(
func,
data['arg'][ind],
data)
minion_instance.functions.pack['__context__']['retcode'] = 0
key = ind if multifunc_ordered else data['fun'][ind]
ret['return'][key] = func(*args, **kwargs)
retcode = minion_instance.functions.pack['__context__'].get(
'retcode',
0
)
if retcode == 0:
# No nonzero retcode in __context__ dunder. Check if return
# is a dictionary with a "result" or "success" key.
try:
func_result = all(ret['return'][key].get(x, True)
for x in ('result', 'success'))
except Exception:
# return data is not a dict
func_result = True
if not func_result:
retcode = 1
ret['retcode'][key] = retcode
ret['success'][key] = retcode == 0
except Exception as exc:
trb = traceback.format_exc()
log.warning('The minion function caused an exception: %s', exc)
if multifunc_ordered:
ret['return'][ind] = trb
else:
ret['return'][data['fun'][ind]] = trb
ret['jid'] = data['jid']
ret['fun'] = data['fun']
ret['fun_args'] = data['arg']
if 'metadata' in data:
ret['metadata'] = data['metadata']
if minion_instance.connected:
minion_instance._return_pub(
ret,
timeout=minion_instance._return_retry_timer()
)
if data['ret']:
if 'ret_config' in data:
ret['ret_config'] = data['ret_config']
if 'ret_kwargs' in data:
ret['ret_kwargs'] = data['ret_kwargs']
for returner in set(data['ret'].split(',')):
ret['id'] = opts['id']
try:
minion_instance.returners['{0}.returner'.format(
returner
)](ret)
except Exception as exc:
log.error(
'The return failed for job %s: %s',
data['jid'], exc
)
def _return_pub(self, ret, ret_cmd='_return', timeout=60, sync=True):
'''
Return the data from the executed command to the master server
'''
jid = ret.get('jid', ret.get('__jid__'))
fun = ret.get('fun', ret.get('__fun__'))
if self.opts['multiprocessing']:
fn_ = os.path.join(self.proc_dir, jid)
if os.path.isfile(fn_):
try:
os.remove(fn_)
except (OSError, IOError):
# The file is gone already
pass
log.info('Returning information for job: %s', jid)
log.trace('Return data: %s', ret)
if ret_cmd == '_syndic_return':
load = {'cmd': ret_cmd,
'id': self.opts['uid'],
'jid': jid,
'fun': fun,
'arg': ret.get('arg'),
'tgt': ret.get('tgt'),
'tgt_type': ret.get('tgt_type'),
'load': ret.get('__load__')}
if '__master_id__' in ret:
load['master_id'] = ret['__master_id__']
load['return'] = {}
for key, value in six.iteritems(ret):
if key.startswith('__'):
continue
load['return'][key] = value
else:
load = {'cmd': ret_cmd,
'id': self.opts['id']}
for key, value in six.iteritems(ret):
load[key] = value
if 'out' in ret:
if isinstance(ret['out'], six.string_types):
load['out'] = ret['out']
else:
log.error(
'Invalid outputter %s. This is likely a bug.',
ret['out']
)
else:
try:
oput = self.functions[fun].__outputter__
except (KeyError, AttributeError, TypeError):
pass
else:
if isinstance(oput, six.string_types):
load['out'] = oput
if self.opts['cache_jobs']:
# Local job cache has been enabled
if ret['jid'] == 'req':
ret['jid'] = salt.utils.jid.gen_jid(self.opts)
salt.utils.minion.cache_jobs(self.opts, ret['jid'], ret)
if not self.opts['pub_ret']:
return ''
def timeout_handler(*_):
log.warning(
'The minion failed to return the job information for job %s. '
'This is often due to the master being shut down or '
'overloaded. If the master is running, consider increasing '
'the worker_threads value.', jid
)
return True
if sync:
try:
ret_val = self._send_req_sync(load, timeout=timeout)
except SaltReqTimeoutError:
timeout_handler()
return ''
else:
with tornado.stack_context.ExceptionStackContext(timeout_handler):
ret_val = self._send_req_async(load, timeout=timeout, callback=lambda f: None) # pylint: disable=unexpected-keyword-arg
log.trace('ret_val = %s', ret_val) # pylint: disable=no-member
return ret_val
def _return_pub_multi(self, rets, ret_cmd='_return', timeout=60, sync=True):
'''
Return the data from the executed command to the master server
'''
if not isinstance(rets, list):
rets = [rets]
jids = {}
for ret in rets:
jid = ret.get('jid', ret.get('__jid__'))
fun = ret.get('fun', ret.get('__fun__'))
if self.opts['multiprocessing']:
fn_ = os.path.join(self.proc_dir, jid)
if os.path.isfile(fn_):
try:
os.remove(fn_)
except (OSError, IOError):
# The file is gone already
pass
log.info('Returning information for job: %s', jid)
load = jids.setdefault(jid, {})
if ret_cmd == '_syndic_return':
if not load:
load.update({'id': self.opts['id'],
'jid': jid,
'fun': fun,
'arg': ret.get('arg'),
'tgt': ret.get('tgt'),
'tgt_type': ret.get('tgt_type'),
'load': ret.get('__load__'),
'return': {}})
if '__master_id__' in ret:
load['master_id'] = ret['__master_id__']
for key, value in six.iteritems(ret):
if key.startswith('__'):
continue
load['return'][key] = value
else:
load.update({'id': self.opts['id']})
for key, value in six.iteritems(ret):
load[key] = value
if 'out' in ret:
if isinstance(ret['out'], six.string_types):
load['out'] = ret['out']
else:
log.error(
'Invalid outputter %s. This is likely a bug.',
ret['out']
)
else:
try:
oput = self.functions[fun].__outputter__
except (KeyError, AttributeError, TypeError):
pass
else:
if isinstance(oput, six.string_types):
load['out'] = oput
if self.opts['cache_jobs']:
# Local job cache has been enabled
salt.utils.minion.cache_jobs(self.opts, load['jid'], ret)
load = {'cmd': ret_cmd,
'load': list(six.itervalues(jids))}
def timeout_handler(*_):
log.warning(
'The minion failed to return the job information for job %s. '
'This is often due to the master being shut down or '
'overloaded. If the master is running, consider increasing '
'the worker_threads value.', jid
)
return True
if sync:
try:
ret_val = self._send_req_sync(load, timeout=timeout)
except SaltReqTimeoutError:
timeout_handler()
return ''
else:
with tornado.stack_context.ExceptionStackContext(timeout_handler):
ret_val = self._send_req_async(load, timeout=timeout, callback=lambda f: None) # pylint: disable=unexpected-keyword-arg
log.trace('ret_val = %s', ret_val) # pylint: disable=no-member
return ret_val
def _state_run(self):
'''
Execute a state run based on information set in the minion config file
'''
if self.opts['startup_states']:
if self.opts.get('master_type', 'str') == 'disable' and \
self.opts.get('file_client', 'remote') == 'remote':
log.warning(
'Cannot run startup_states when \'master_type\' is set '
'to \'disable\' and \'file_client\' is set to '
'\'remote\'. Skipping.'
)
else:
data = {'jid': 'req', 'ret': self.opts.get('ext_job_cache', '')}
if self.opts['startup_states'] == 'sls':
data['fun'] = 'state.sls'
data['arg'] = [self.opts['sls_list']]
elif self.opts['startup_states'] == 'top':
data['fun'] = 'state.top'
data['arg'] = [self.opts['top_file']]
else:
data['fun'] = 'state.highstate'
data['arg'] = []
self._handle_decoded_payload(data)
def _refresh_grains_watcher(self, refresh_interval_in_minutes):
'''
Create a loop that will fire a pillar refresh to inform a master about a change in the grains of this minion
:param refresh_interval_in_minutes:
:return: None
'''
if '__update_grains' not in self.opts.get('schedule', {}):
if 'schedule' not in self.opts:
self.opts['schedule'] = {}
self.opts['schedule'].update({
'__update_grains':
{
'function': 'event.fire',
'args': [{}, 'grains_refresh'],
'minutes': refresh_interval_in_minutes
}
})
def _fire_master_minion_start(self):
# Send an event to the master that the minion is live
if self.opts['enable_legacy_startup_events']:
# Old style event. Defaults to False in Sodium release.
self._fire_master(
'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
'minion_start'
)
# send name spaced event
self._fire_master(
'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
tagify([self.opts['id'], 'start'], 'minion'),
)
def module_refresh(self, force_refresh=False, notify=False):
'''
Refresh the functions and returners.
'''
log.debug('Refreshing modules. Notify=%s', notify)
self.functions, self.returners, _, self.executors = self._load_modules(force_refresh, notify=notify)
self.schedule.functions = self.functions
self.schedule.returners = self.returners
def beacons_refresh(self):
'''
Refresh the functions and returners.
'''
log.debug('Refreshing beacons.')
self.beacons = salt.beacons.Beacon(self.opts, self.functions)
def matchers_refresh(self):
'''
Refresh the matchers
'''
log.debug('Refreshing matchers.')
self.matchers = salt.loader.matchers(self.opts)
# TODO: only allow one future in flight at a time?
@tornado.gen.coroutine
def pillar_refresh(self, force_refresh=False, notify=False):
'''
Refresh the pillar
'''
if self.connected:
log.debug('Refreshing pillar. Notify: %s', notify)
async_pillar = salt.pillar.get_async_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillarenv=self.opts.get('pillarenv'),
)
try:
self.opts['pillar'] = yield async_pillar.compile_pillar()
if notify:
evt = salt.utils.event.get_event('minion', opts=self.opts, listen=False)
evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_PILLAR_COMPLETE)
except SaltClientError:
# Do not exit if a pillar refresh fails.
log.error('Pillar data could not be refreshed. '
'One or more masters may be down!')
finally:
async_pillar.destroy()
self.module_refresh(force_refresh, notify)
self.matchers_refresh()
self.beacons_refresh()
def manage_schedule(self, tag, data):
'''
Refresh the functions and returners.
'''
func = data.get('func', None)
name = data.get('name', None)
schedule = data.get('schedule', None)
where = data.get('where', None)
persist = data.get('persist', None)
funcs = {'delete': ('delete_job', (name, persist)),
'add': ('add_job', (schedule, persist)),
'modify': ('modify_job',
(name, schedule, persist)),
'enable': ('enable_schedule', ()),
'disable': ('disable_schedule', ()),
'enable_job': ('enable_job', (name, persist)),
'disable_job': ('disable_job', (name, persist)),
'postpone_job': ('postpone_job', (name, data)),
'skip_job': ('skip_job', (name, data)),
'reload': ('reload', (schedule,)),
'list': ('list', (where,)),
'save_schedule': ('save_schedule', ()),
'get_next_fire_time': ('get_next_fire_time',
(name,))}
# Call the appropriate schedule function
try:
alias, params = funcs.get(func)
getattr(self.schedule, alias)(*params)
except TypeError:
log.error('Function "%s" is unavailable in salt.utils.scheduler',
func)
def manage_beacons(self, tag, data):
'''
Manage Beacons
'''
func = data.get('func', None)
name = data.get('name', None)
beacon_data = data.get('beacon_data', None)
include_pillar = data.get('include_pillar', None)
include_opts = data.get('include_opts', None)
funcs = {'add': ('add_beacon', (name, beacon_data)),
'modify': ('modify_beacon', (name, beacon_data)),
'delete': ('delete_beacon', (name,)),
'enable': ('enable_beacons', ()),
'disable': ('disable_beacons', ()),
'enable_beacon': ('enable_beacon', (name,)),
'disable_beacon': ('disable_beacon', (name,)),
'list': ('list_beacons', (include_opts,
include_pillar)),
'list_available': ('list_available_beacons', ()),
'validate_beacon': ('validate_beacon', (name,
beacon_data)),
'reset': ('reset', ())}
# Call the appropriate beacon function
try:
alias, params = funcs.get(func)
getattr(self.beacons, alias)(*params)
except AttributeError:
log.error('Function "%s" is unavailable in salt.beacons', func)
except TypeError as exc:
log.info(
'Failed to handle %s with data(%s). Error: %s',
tag, data, exc,
exc_info_on_loglevel=logging.DEBUG
)
def environ_setenv(self, tag, data):
'''
Set the salt-minion main process environment according to
the data contained in the minion event data
'''
environ = data.get('environ', None)
if environ is None:
return False
false_unsets = data.get('false_unsets', False)
clear_all = data.get('clear_all', False)
import salt.modules.environ as mod_environ
return mod_environ.setenv(environ, false_unsets, clear_all)
def _pre_tune(self):
'''
Set the minion running flag and issue the appropriate warnings if
the minion cannot be started or is already running
'''
if self._running is None:
self._running = True
elif self._running is False:
log.error(
'This %s was scheduled to stop. Not running %s.tune_in()',
self.__class__.__name__, self.__class__.__name__
)
return
elif self._running is True:
log.error(
'This %s is already running. Not running %s.tune_in()',
self.__class__.__name__, self.__class__.__name__
)
return
try:
log.info(
'%s is starting as user \'%s\'',
self.__class__.__name__, salt.utils.user.get_user()
)
except Exception as err:
# Only windows is allowed to fail here. See #3189. Log as debug in
# that case. Else, error.
log.log(
salt.utils.platform.is_windows() and logging.DEBUG or logging.ERROR,
'Failed to get the user who is starting %s',
self.__class__.__name__,
exc_info=err
)
def _mine_send(self, tag, data):
'''
Send mine data to the master
'''
channel = salt.transport.client.ReqChannel.factory(self.opts)
data['tok'] = self.tok
try:
ret = channel.send(data)
return ret
except SaltReqTimeoutError:
log.warning('Unable to send mine data to master.')
return None
finally:
channel.close()
def _handle_tag_module_refresh(self, tag, data):
'''
Handle a module_refresh event
'''
self.module_refresh(
force_refresh=data.get('force_refresh', False),
notify=data.get('notify', False)
)
@tornado.gen.coroutine
def _handle_tag_pillar_refresh(self, tag, data):
'''
Handle a pillar_refresh event
'''
yield self.pillar_refresh(
force_refresh=data.get('force_refresh', False),
notify=data.get('notify', False)
)
def _handle_tag_beacons_refresh(self, tag, data):
'''
Handle a beacon_refresh event
'''
self.beacons_refresh()
def _handle_tag_matchers_refresh(self, tag, data):
'''
Handle a matchers_refresh event
'''
self.matchers_refresh()
def _handle_tag_manage_schedule(self, tag, data):
'''
Handle a manage_schedule event
'''
self.manage_schedule(tag, data)
def _handle_tag_manage_beacons(self, tag, data):
'''
Handle a manage_beacons event
'''
self.manage_beacons(tag, data)
def _handle_tag_grains_refresh(self, tag, data):
'''
Handle a grains_refresh event
'''
if (data.get('force_refresh', False) or
self.grains_cache != self.opts['grains']):
self.pillar_refresh(force_refresh=True)
self.grains_cache = self.opts['grains']
def _handle_tag_environ_setenv(self, tag, data):
'''
Handle a environ_setenv event
'''
self.environ_setenv(tag, data)
def _handle_tag_minion_mine(self, tag, data):
'''
Handle a _minion_mine event
'''
self._mine_send(tag, data)
def _handle_tag_fire_master(self, tag, data):
'''
Handle a fire_master event
'''
if self.connected:
log.debug('Forwarding master event tag=%s', data['tag'])
self._fire_master(data['data'], data['tag'], data['events'], data['pretag'])
def _handle_tag_master_disconnected_failback(self, tag, data):
'''
Handle a master_disconnected_failback event
'''
# if the master disconnect event is for a different master, raise an exception
if tag.startswith(master_event(type='disconnected')) and data['master'] != self.opts['master']:
# not mine master, ignore
return
if tag.startswith(master_event(type='failback')):
# if the master failback event is not for the top master, raise an exception
if data['master'] != self.opts['master_list'][0]:
raise SaltException('Bad master \'{0}\' when mine failback is \'{1}\''.format(
data['master'], self.opts['master']))
# if the master failback event is for the current master, raise an exception
elif data['master'] == self.opts['master'][0]:
raise SaltException('Already connected to \'{0}\''.format(data['master']))
if self.connected:
# we are not connected anymore
self.connected = False
log.info('Connection to master %s lost', self.opts['master'])
# we can't use the config default here because the default '0' value is overloaded
# to mean 'if 0 disable the job', but when salt detects a timeout it also sets up
# these jobs
master_alive_interval = self.opts['master_alive_interval'] or 60
if self.opts['master_type'] != 'failover':
# modify the scheduled job to fire on reconnect
if self.opts['transport'] != 'tcp':
schedule = {
'function': 'status.master',
'seconds': master_alive_interval,
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master'],
'connected': False}
}
self.schedule.modify_job(name=master_event(type='alive', master=self.opts['master']),
schedule=schedule)
else:
# delete the scheduled job to don't interfere with the failover process
if self.opts['transport'] != 'tcp':
self.schedule.delete_job(name=master_event(type='alive', master=self.opts['master']),
persist=True)
log.info('Trying to tune in to next master from master-list')
if hasattr(self, 'pub_channel'):
self.pub_channel.on_recv(None)
if hasattr(self.pub_channel, 'auth'):
self.pub_channel.auth.invalidate()
if hasattr(self.pub_channel, 'close'):
self.pub_channel.close()
del self.pub_channel
# if eval_master finds a new master for us, self.connected
# will be True again on successful master authentication
try:
master, self.pub_channel = yield self.eval_master(
opts=self.opts,
failed=True,
failback=tag.startswith(master_event(type='failback')))
except SaltClientError:
pass
if self.connected:
self.opts['master'] = master
# re-init the subsystems to work with the new master
log.info(
'Re-initialising subsystems for new master %s',
self.opts['master']
)
# put the current schedule into the new loaders
self.opts['schedule'] = self.schedule.option('schedule')
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
# make the schedule to use the new 'functions' loader
self.schedule.functions = self.functions
self.pub_channel.on_recv(self._handle_payload)
self._fire_master_minion_start()
log.info('Minion is ready to receive requests!')
# update scheduled job to run with the new master addr
if self.opts['transport'] != 'tcp':
schedule = {
'function': 'status.master',
'seconds': master_alive_interval,
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master'],
'connected': True}
}
self.schedule.modify_job(name=master_event(type='alive', master=self.opts['master']),
schedule=schedule)
if self.opts['master_failback'] and 'master_list' in self.opts:
if self.opts['master'] != self.opts['master_list'][0]:
schedule = {
'function': 'status.ping_master',
'seconds': self.opts['master_failback_interval'],
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master_list'][0]}
}
self.schedule.modify_job(name=master_event(type='failback'),
schedule=schedule)
else:
self.schedule.delete_job(name=master_event(type='failback'), persist=True)
else:
self.restart = True
self.io_loop.stop()
def _handle_tag_master_connected(self, tag, data):
'''
Handle a master_connected event
'''
# handle this event only once. otherwise it will pollute the log
# also if master type is failover all the reconnection work is done
# by `disconnected` event handler and this event must never happen,
# anyway check it to be sure
if not self.connected and self.opts['master_type'] != 'failover':
log.info('Connection to master %s re-established', self.opts['master'])
self.connected = True
# modify the __master_alive job to only fire,
# if the connection is lost again
if self.opts['transport'] != 'tcp':
if self.opts['master_alive_interval'] > 0:
schedule = {
'function': 'status.master',
'seconds': self.opts['master_alive_interval'],
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master'],
'connected': True}
}
self.schedule.modify_job(name=master_event(type='alive', master=self.opts['master']),
schedule=schedule)
else:
self.schedule.delete_job(name=master_event(type='alive', master=self.opts['master']), persist=True)
def _handle_tag_schedule_return(self, tag, data):
'''
Handle a _schedule_return event
'''
# reporting current connection with master
if data['schedule'].startswith(master_event(type='alive', master='')):
if data['return']:
log.debug(
'Connected to master %s',
data['schedule'].split(master_event(type='alive', master=''))[1]
)
self._return_pub(data, ret_cmd='_return', sync=False)
def _handle_tag_salt_error(self, tag, data):
'''
Handle a _salt_error event
'''
if self.connected:
log.debug('Forwarding salt error event tag=%s', tag)
self._fire_master(data, tag)
def _handle_tag_salt_auth_creds(self, tag, data):
'''
Handle a salt_auth_creds event
'''
key = tuple(data['key'])
log.debug(
'Updating auth data for %s: %s -> %s',
key, salt.crypt.AsyncAuth.creds_map.get(key), data['creds']
)
salt.crypt.AsyncAuth.creds_map[tuple(data['key'])] = data['creds']
@tornado.gen.coroutine
def handle_event(self, package):
'''
Handle an event from the epull_sock (all local minion events)
'''
if not self.ready:
raise tornado.gen.Return()
tag, data = salt.utils.event.SaltEvent.unpack(package)
log.debug(
'Minion of \'%s\' is handling event tag \'%s\'',
self.opts['master'], tag
)
tag_functions = {
'beacons_refresh': self._handle_tag_beacons_refresh,
'environ_setenv': self._handle_tag_environ_setenv,
'fire_master': self._handle_tag_fire_master,
'grains_refresh': self._handle_tag_grains_refresh,
'matchers_refresh': self._handle_tag_matchers_refresh,
'manage_schedule': self._handle_tag_manage_schedule,
'manage_beacons': self._handle_tag_manage_beacons,
'_minion_mine': self._handle_tag_minion_mine,
'module_refresh': self._handle_tag_module_refresh,
'pillar_refresh': self._handle_tag_pillar_refresh,
'salt/auth/creds': self._handle_tag_salt_auth_creds,
'_salt_error': self._handle_tag_salt_error,
'__schedule_return': self._handle_tag_schedule_return,
master_event(type='disconnected'): self._handle_tag_master_disconnected_failback,
master_event(type='failback'): self._handle_tag_master_disconnected_failback,
master_event(type='connected'): self._handle_tag_master_connected,
}
# Run the appropriate function
for tag_function in tag_functions:
if tag.startswith(tag_function):
tag_functions[tag_function](tag, data)
def _fallback_cleanups(self):
'''
Fallback cleanup routines, attempting to fix leaked processes, threads, etc.
'''
# Add an extra fallback in case a forked process leaks through
multiprocessing.active_children()
# Cleanup Windows threads
if not salt.utils.platform.is_windows():
return
for thread in self.win_proc:
if not thread.is_alive():
thread.join()
try:
self.win_proc.remove(thread)
del thread
except (ValueError, NameError):
pass
def _setup_core(self):
'''
Set up the core minion attributes.
This is safe to call multiple times.
'''
if not self.ready:
# First call. Initialize.
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
self.serial = salt.payload.Serial(self.opts)
self.mod_opts = self._prep_mod_opts()
# self.matcher = Matcher(self.opts, self.functions)
self.matchers = salt.loader.matchers(self.opts)
self.beacons = salt.beacons.Beacon(self.opts, self.functions)
uid = salt.utils.user.get_uid(user=self.opts.get('user', None))
self.proc_dir = get_proc_dir(self.opts['cachedir'], uid=uid)
self.grains_cache = self.opts['grains']
self.ready = True
def setup_beacons(self, before_connect=False):
'''
Set up the beacons.
This is safe to call multiple times.
'''
self._setup_core()
loop_interval = self.opts['loop_interval']
new_periodic_callbacks = {}
if 'beacons' not in self.periodic_callbacks:
self.beacons = salt.beacons.Beacon(self.opts, self.functions)
def handle_beacons():
# Process Beacons
beacons = None
try:
beacons = self.process_beacons(self.functions)
except Exception:
log.critical('The beacon errored: ', exc_info=True)
if beacons and self.connected:
self._fire_master(events=beacons)
new_periodic_callbacks['beacons'] = tornado.ioloop.PeriodicCallback(
handle_beacons, loop_interval * 1000)
if before_connect:
# Make sure there is a chance for one iteration to occur before connect
handle_beacons()
if 'cleanup' not in self.periodic_callbacks:
new_periodic_callbacks['cleanup'] = tornado.ioloop.PeriodicCallback(
self._fallback_cleanups, loop_interval * 1000)
# start all the other callbacks
for periodic_cb in six.itervalues(new_periodic_callbacks):
periodic_cb.start()
self.periodic_callbacks.update(new_periodic_callbacks)
def setup_scheduler(self, before_connect=False):
'''
Set up the scheduler.
This is safe to call multiple times.
'''
self._setup_core()
loop_interval = self.opts['loop_interval']
new_periodic_callbacks = {}
if 'schedule' not in self.periodic_callbacks:
if 'schedule' not in self.opts:
self.opts['schedule'] = {}
if not hasattr(self, 'schedule'):
self.schedule = salt.utils.schedule.Schedule(
self.opts,
self.functions,
self.returners,
utils=self.utils,
cleanup=[master_event(type='alive')])
try:
if self.opts['grains_refresh_every']: # In minutes, not seconds!
log.debug(
'Enabling the grains refresher. Will run every %d minute(s).',
self.opts['grains_refresh_every']
)
self._refresh_grains_watcher(abs(self.opts['grains_refresh_every']))
except Exception as exc:
log.error(
'Exception occurred in attempt to initialize grain refresh '
'routine during minion tune-in: %s', exc
)
# TODO: actually listen to the return and change period
def handle_schedule():
self.process_schedule(self, loop_interval)
new_periodic_callbacks['schedule'] = tornado.ioloop.PeriodicCallback(handle_schedule, 1000)
if before_connect:
# Make sure there is a chance for one iteration to occur before connect
handle_schedule()
if 'cleanup' not in self.periodic_callbacks:
new_periodic_callbacks['cleanup'] = tornado.ioloop.PeriodicCallback(
self._fallback_cleanups, loop_interval * 1000)
# start all the other callbacks
for periodic_cb in six.itervalues(new_periodic_callbacks):
periodic_cb.start()
self.periodic_callbacks.update(new_periodic_callbacks)
# Main Minion Tune In
def tune_in(self, start=True):
'''
Lock onto the publisher. This is the main event loop for the minion
:rtype : None
'''
self._pre_tune()
log.debug('Minion \'%s\' trying to tune in', self.opts['id'])
if start:
if self.opts.get('beacons_before_connect', False):
self.setup_beacons(before_connect=True)
if self.opts.get('scheduler_before_connect', False):
self.setup_scheduler(before_connect=True)
self.sync_connect_master()
if self.connected:
self._fire_master_minion_start()
log.info('Minion is ready to receive requests!')
# Make sure to gracefully handle SIGUSR1
enable_sigusr1_handler()
# Make sure to gracefully handle CTRL_LOGOFF_EVENT
if HAS_WIN_FUNCTIONS:
salt.utils.win_functions.enable_ctrl_logoff_handler()
# On first startup execute a state run if configured to do so
self._state_run()
self.setup_beacons()
self.setup_scheduler()
# schedule the stuff that runs every interval
ping_interval = self.opts.get('ping_interval', 0) * 60
if ping_interval > 0 and self.connected:
def ping_master():
try:
def ping_timeout_handler(*_):
if self.opts.get('auth_safemode', False):
log.error('** Master Ping failed. Attempting to restart minion**')
delay = self.opts.get('random_reauth_delay', 5)
log.info('delaying random_reauth_delay %ss', delay)
try:
self.functions['service.restart'](service_name())
except KeyError:
# Probably no init system (running in docker?)
log.warning(
'ping_interval reached without response '
'from the master, but service.restart '
'could not be run to restart the minion '
'daemon. ping_interval requires that the '
'minion is running under an init system.'
)
self._fire_master('ping', 'minion_ping', sync=False, timeout_handler=ping_timeout_handler)
except Exception:
log.warning('Attempt to ping master failed.', exc_on_loglevel=logging.DEBUG)
self.periodic_callbacks['ping'] = tornado.ioloop.PeriodicCallback(ping_master, ping_interval * 1000)
self.periodic_callbacks['ping'].start()
# add handler to subscriber
if hasattr(self, 'pub_channel') and self.pub_channel is not None:
self.pub_channel.on_recv(self._handle_payload)
elif self.opts.get('master_type') != 'disable':
log.error('No connection to master found. Scheduled jobs will not run.')
if start:
try:
self.io_loop.start()
if self.restart:
self.destroy()
except (KeyboardInterrupt, RuntimeError): # A RuntimeError can be re-raised by Tornado on shutdown
self.destroy()
def _handle_payload(self, payload):
if payload is not None and payload['enc'] == 'aes':
if self._target_load(payload['load']):
self._handle_decoded_payload(payload['load'])
elif self.opts['zmq_filtering']:
# In the filtering enabled case, we'd like to know when minion sees something it shouldnt
log.trace(
'Broadcast message received not for this minion, Load: %s',
payload['load']
)
# If it's not AES, and thus has not been verified, we do nothing.
# In the future, we could add support for some clearfuncs, but
# the minion currently has no need.
def _target_load(self, load):
# Verify that the publication is valid
if 'tgt' not in load or 'jid' not in load or 'fun' not in load \
or 'arg' not in load:
return False
# Verify that the publication applies to this minion
# It's important to note that the master does some pre-processing
# to determine which minions to send a request to. So for example,
# a "salt -G 'grain_key:grain_val' test.ping" will invoke some
# pre-processing on the master and this minion should not see the
# publication if the master does not determine that it should.
if 'tgt_type' in load:
match_func = self.matchers.get('{0}_match.match'.format(load['tgt_type']), None)
if match_func is None:
return False
if load['tgt_type'] in ('grain', 'grain_pcre', 'pillar'):
delimiter = load.get('delimiter', DEFAULT_TARGET_DELIM)
if not match_func(load['tgt'], delimiter=delimiter):
return False
elif not match_func(load['tgt']):
return False
else:
if not self.matchers['glob_match.match'](load['tgt']):
return False
return True
def destroy(self):
'''
Tear down the minion
'''
if self._running is False:
return
self._running = False
if hasattr(self, 'schedule'):
del self.schedule
if hasattr(self, 'pub_channel') and self.pub_channel is not None:
self.pub_channel.on_recv(None)
if hasattr(self.pub_channel, 'close'):
self.pub_channel.close()
del self.pub_channel
if hasattr(self, 'periodic_callbacks'):
for cb in six.itervalues(self.periodic_callbacks):
cb.stop()
def __del__(self):
self.destroy()
class Syndic(Minion):
'''
Make a Syndic minion, this minion will use the minion keys on the
master to authenticate with a higher level master.
'''
def __init__(self, opts, **kwargs):
self._syndic_interface = opts.get('interface')
self._syndic = True
# force auth_safemode True because Syndic don't support autorestart
opts['auth_safemode'] = True
opts['loop_interval'] = 1
super(Syndic, self).__init__(opts, **kwargs)
self.mminion = salt.minion.MasterMinion(opts)
self.jid_forward_cache = set()
self.jids = {}
self.raw_events = []
self.pub_future = None
def _handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
# TODO: even do this??
data['to'] = int(data.get('to', self.opts['timeout'])) - 1
# Only forward the command if it didn't originate from ourselves
if data.get('master_id', 0) != self.opts.get('master_id', 1):
self.syndic_cmd(data)
def syndic_cmd(self, data):
'''
Take the now clear load and forward it on to the client cmd
'''
# Set up default tgt_type
if 'tgt_type' not in data:
data['tgt_type'] = 'glob'
kwargs = {}
# optionally add a few fields to the publish data
for field in ('master_id', # which master the job came from
'user', # which user ran the job
):
if field in data:
kwargs[field] = data[field]
def timeout_handler(*args):
log.warning('Unable to forward pub data: %s', args[1])
return True
with tornado.stack_context.ExceptionStackContext(timeout_handler):
self.local.pub_async(data['tgt'],
data['fun'],
data['arg'],
data['tgt_type'],
data['ret'],
data['jid'],
data['to'],
io_loop=self.io_loop,
callback=lambda _: None,
**kwargs)
def fire_master_syndic_start(self):
# Send an event to the master that the minion is live
if self.opts['enable_legacy_startup_events']:
# Old style event. Defaults to false in Sodium release.
self._fire_master(
'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
'syndic_start',
sync=False,
)
self._fire_master(
'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
tagify([self.opts['id'], 'start'], 'syndic'),
sync=False,
)
# TODO: clean up docs
def tune_in_no_block(self):
'''
Executes the tune_in sequence but omits extra logging and the
management of the event bus assuming that these are handled outside
the tune_in sequence
'''
# Instantiate the local client
self.local = salt.client.get_local_client(
self.opts['_minion_conf_file'], io_loop=self.io_loop)
# add handler to subscriber
self.pub_channel.on_recv(self._process_cmd_socket)
def _process_cmd_socket(self, payload):
if payload is not None and payload['enc'] == 'aes':
log.trace('Handling payload')
self._handle_decoded_payload(payload['load'])
# If it's not AES, and thus has not been verified, we do nothing.
# In the future, we could add support for some clearfuncs, but
# the syndic currently has no need.
@tornado.gen.coroutine
def reconnect(self):
if hasattr(self, 'pub_channel'):
self.pub_channel.on_recv(None)
if hasattr(self.pub_channel, 'close'):
self.pub_channel.close()
del self.pub_channel
# if eval_master finds a new master for us, self.connected
# will be True again on successful master authentication
master, self.pub_channel = yield self.eval_master(opts=self.opts)
if self.connected:
self.opts['master'] = master
self.pub_channel.on_recv(self._process_cmd_socket)
log.info('Minion is ready to receive requests!')
raise tornado.gen.Return(self)
def destroy(self):
'''
Tear down the syndic minion
'''
# We borrowed the local clients poller so give it back before
# it's destroyed. Reset the local poller reference.
super(Syndic, self).destroy()
if hasattr(self, 'local'):
del self.local
if hasattr(self, 'forward_events'):
self.forward_events.stop()
# TODO: need a way of knowing if the syndic connection is busted
class SyndicManager(MinionBase):
'''
Make a MultiMaster syndic minion, this minion will handle relaying jobs and returns from
all minions connected to it to the list of masters it is connected to.
Modes (controlled by `syndic_mode`:
sync: This mode will synchronize all events and publishes from higher level masters
cluster: This mode will only sync job publishes and returns
Note: jobs will be returned best-effort to the requesting master. This also means
(since we are using zmq) that if a job was fired and the master disconnects
between the publish and return, that the return will end up in a zmq buffer
in this Syndic headed to that original master.
In addition, since these classes all seem to use a mix of blocking and non-blocking
calls (with varying timeouts along the way) this daemon does not handle failure well,
it will (under most circumstances) stall the daemon for ~15s trying to forward events
to the down master
'''
# time to connect to upstream master
SYNDIC_CONNECT_TIMEOUT = 5
SYNDIC_EVENT_TIMEOUT = 5
def __init__(self, opts, io_loop=None):
opts['loop_interval'] = 1
super(SyndicManager, self).__init__(opts)
self.mminion = salt.minion.MasterMinion(opts)
# sync (old behavior), cluster (only returns and publishes)
self.syndic_mode = self.opts.get('syndic_mode', 'sync')
self.syndic_failover = self.opts.get('syndic_failover', 'random')
self.auth_wait = self.opts['acceptance_wait_time']
self.max_auth_wait = self.opts['acceptance_wait_time_max']
self._has_master = threading.Event()
self.jid_forward_cache = set()
if io_loop is None:
install_zmq()
self.io_loop = ZMQDefaultLoop.current()
else:
self.io_loop = io_loop
# List of events
self.raw_events = []
# Dict of rets: {master_id: {event_tag: job_ret, ...}, ...}
self.job_rets = {}
# List of delayed job_rets which was unable to send for some reason and will be resend to
# any available master
self.delayed = []
# Active pub futures: {master_id: (future, [job_ret, ...]), ...}
self.pub_futures = {}
def _spawn_syndics(self):
'''
Spawn all the coroutines which will sign in the syndics
'''
self._syndics = OrderedDict() # mapping of opts['master'] -> syndic
masters = self.opts['master']
if not isinstance(masters, list):
masters = [masters]
for master in masters:
s_opts = copy.copy(self.opts)
s_opts['master'] = master
self._syndics[master] = self._connect_syndic(s_opts)
@tornado.gen.coroutine
def _connect_syndic(self, opts):
'''
Create a syndic, and asynchronously connect it to a master
'''
auth_wait = opts['acceptance_wait_time']
failed = False
while True:
if failed:
if auth_wait < self.max_auth_wait:
auth_wait += self.auth_wait
log.debug(
"sleeping before reconnect attempt to %s [%d/%d]",
opts['master'],
auth_wait,
self.max_auth_wait,
)
yield tornado.gen.sleep(auth_wait) # TODO: log?
log.debug(
'Syndic attempting to connect to %s',
opts['master']
)
try:
syndic = Syndic(opts,
timeout=self.SYNDIC_CONNECT_TIMEOUT,
safe=False,
io_loop=self.io_loop,
)
yield syndic.connect_master(failed=failed)
# set up the syndic to handle publishes (specifically not event forwarding)
syndic.tune_in_no_block()
# Send an event to the master that the minion is live
syndic.fire_master_syndic_start()
log.info(
'Syndic successfully connected to %s',
opts['master']
)
break
except SaltClientError as exc:
failed = True
log.error(
'Error while bringing up syndic for multi-syndic. Is the '
'master at %s responding?', opts['master']
)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
failed = True
log.critical(
'Unexpected error while connecting to %s',
opts['master'], exc_info=True
)
raise tornado.gen.Return(syndic)
def _mark_master_dead(self, master):
'''
Mark a master as dead. This will start the sign-in routine
'''
# if its connected, mark it dead
if self._syndics[master].done():
syndic = self._syndics[master].result() # pylint: disable=no-member
self._syndics[master] = syndic.reconnect()
else:
# TODO: debug?
log.info(
'Attempting to mark %s as dead, although it is already '
'marked dead', master
)
def _call_syndic(self, func, args=(), kwargs=None, master_id=None):
'''
Wrapper to call a given func on a syndic, best effort to get the one you asked for
'''
if kwargs is None:
kwargs = {}
successful = False
# Call for each master
for master, syndic_future in self.iter_master_options(master_id):
if not syndic_future.done() or syndic_future.exception():
log.error(
'Unable to call %s on %s, that syndic is not connected',
func, master
)
continue
try:
getattr(syndic_future.result(), func)(*args, **kwargs)
successful = True
except SaltClientError:
log.error(
'Unable to call %s on %s, trying another...',
func, master
)
self._mark_master_dead(master)
if not successful:
log.critical('Unable to call %s on any masters!', func)
def _return_pub_syndic(self, values, master_id=None):
'''
Wrapper to call the '_return_pub_multi' a syndic, best effort to get the one you asked for
'''
func = '_return_pub_multi'
for master, syndic_future in self.iter_master_options(master_id):
if not syndic_future.done() or syndic_future.exception():
log.error(
'Unable to call %s on %s, that syndic is not connected',
func, master
)
continue
future, data = self.pub_futures.get(master, (None, None))
if future is not None:
if not future.done():
if master == master_id:
# Targeted master previous send not done yet, call again later
return False
else:
# Fallback master is busy, try the next one
continue
elif future.exception():
# Previous execution on this master returned an error
log.error(
'Unable to call %s on %s, trying another...',
func, master
)
self._mark_master_dead(master)
del self.pub_futures[master]
# Add not sent data to the delayed list and try the next master
self.delayed.extend(data)
continue
future = getattr(syndic_future.result(), func)(values,
'_syndic_return',
timeout=self._return_retry_timer(),
sync=False)
self.pub_futures[master] = (future, values)
return True
# Loop done and didn't exit: wasn't sent, try again later
return False
def iter_master_options(self, master_id=None):
'''
Iterate (in order) over your options for master
'''
masters = list(self._syndics.keys())
if self.opts['syndic_failover'] == 'random':
shuffle(masters)
if master_id not in self._syndics:
master_id = masters.pop(0)
else:
masters.remove(master_id)
while True:
yield master_id, self._syndics[master_id]
if not masters:
break
master_id = masters.pop(0)
def _reset_event_aggregation(self):
self.job_rets = {}
self.raw_events = []
def reconnect_event_bus(self, something):
future = self.local.event.set_event_handler(self._process_event)
self.io_loop.add_future(future, self.reconnect_event_bus)
# Syndic Tune In
def tune_in(self):
'''
Lock onto the publisher. This is the main event loop for the syndic
'''
self._spawn_syndics()
# Instantiate the local client
self.local = salt.client.get_local_client(
self.opts['_minion_conf_file'], io_loop=self.io_loop)
self.local.event.subscribe('')
log.debug('SyndicManager \'%s\' trying to tune in', self.opts['id'])
# register the event sub to the poller
self.job_rets = {}
self.raw_events = []
self._reset_event_aggregation()
future = self.local.event.set_event_handler(self._process_event)
self.io_loop.add_future(future, self.reconnect_event_bus)
# forward events every syndic_event_forward_timeout
self.forward_events = tornado.ioloop.PeriodicCallback(self._forward_events,
self.opts['syndic_event_forward_timeout'] * 1000,
)
self.forward_events.start()
# Make sure to gracefully handle SIGUSR1
enable_sigusr1_handler()
self.io_loop.start()
def _process_event(self, raw):
# TODO: cleanup: Move down into event class
mtag, data = self.local.event.unpack(raw, self.local.event.serial)
log.trace('Got event %s', mtag) # pylint: disable=no-member
tag_parts = mtag.split('/')
if len(tag_parts) >= 4 and tag_parts[1] == 'job' and \
salt.utils.jid.is_jid(tag_parts[2]) and tag_parts[3] == 'ret' and \
'return' in data:
if 'jid' not in data:
# Not a job return
return
if self.syndic_mode == 'cluster' and data.get('master_id', 0) == self.opts.get('master_id', 1):
log.debug('Return received with matching master_id, not forwarding')
return
master = data.get('master_id')
jdict = self.job_rets.setdefault(master, {}).setdefault(mtag, {})
if not jdict:
jdict['__fun__'] = data.get('fun')
jdict['__jid__'] = data['jid']
jdict['__load__'] = {}
fstr = '{0}.get_load'.format(self.opts['master_job_cache'])
# Only need to forward each load once. Don't hit the disk
# for every minion return!
if data['jid'] not in self.jid_forward_cache:
jdict['__load__'].update(
self.mminion.returners[fstr](data['jid'])
)
self.jid_forward_cache.add(data['jid'])
if len(self.jid_forward_cache) > self.opts['syndic_jid_forward_cache_hwm']:
# Pop the oldest jid from the cache
tmp = sorted(list(self.jid_forward_cache))
tmp.pop(0)
self.jid_forward_cache = set(tmp)
if master is not None:
# __'s to make sure it doesn't print out on the master cli
jdict['__master_id__'] = master
ret = {}
for key in 'return', 'retcode', 'success':
if key in data:
ret[key] = data[key]
jdict[data['id']] = ret
else:
# TODO: config to forward these? If so we'll have to keep track of who
# has seen them
# if we are the top level masters-- don't forward all the minion events
if self.syndic_mode == 'sync':
# Add generic event aggregation here
if 'retcode' not in data:
self.raw_events.append({'data': data, 'tag': mtag})
def _forward_events(self):
log.trace('Forwarding events') # pylint: disable=no-member
if self.raw_events:
events = self.raw_events
self.raw_events = []
self._call_syndic('_fire_master',
kwargs={'events': events,
'pretag': tagify(self.opts['id'], base='syndic'),
'timeout': self._return_retry_timer(),
'sync': False,
},
)
if self.delayed:
res = self._return_pub_syndic(self.delayed)
if res:
self.delayed = []
for master in list(six.iterkeys(self.job_rets)):
values = list(six.itervalues(self.job_rets[master]))
res = self._return_pub_syndic(values, master_id=master)
if res:
del self.job_rets[master]
class ProxyMinionManager(MinionManager):
'''
Create the multi-minion interface but for proxy minions
'''
def _create_minion_object(self, opts, timeout, safe,
io_loop=None, loaded_base_name=None,
jid_queue=None):
'''
Helper function to return the correct type of object
'''
return ProxyMinion(opts,
timeout,
safe,
io_loop=io_loop,
loaded_base_name=loaded_base_name,
jid_queue=jid_queue)
def _metaproxy_call(opts, fn_name):
metaproxy = salt.loader.metaproxy(opts)
try:
metaproxy_name = opts['metaproxy']
except KeyError:
metaproxy_name = 'proxy'
log.trace(
'No metaproxy key found in opts for id %s. '
'Defaulting to standard proxy minion.',
opts['id']
)
metaproxy_fn = metaproxy_name + '.' + fn_name
return metaproxy[metaproxy_fn]
class ProxyMinion(Minion):
'''
This class instantiates a 'proxy' minion--a minion that does not manipulate
the host it runs on, but instead manipulates a device that cannot run a minion.
'''
# TODO: better name...
@tornado.gen.coroutine
def _post_master_init(self, master):
'''
Function to finish init after connecting to a master
This is primarily loading modules, pillars, etc. (since they need
to know which master they connected to)
If this function is changed, please check Minion._post_master_init
to see if those changes need to be propagated.
ProxyMinions need a significantly different post master setup,
which is why the differences are not factored out into separate helper
functions.
'''
mp_call = _metaproxy_call(self.opts, 'post_master_init')
return mp_call(self, master)
def _target_load(self, load):
'''
Verify that the publication is valid and applies to this minion
'''
mp_call = _metaproxy_call(self.opts, 'target_load')
return mp_call(self, load)
def _handle_payload(self, payload):
mp_call = _metaproxy_call(self.opts, 'handle_payload')
return mp_call(self, payload)
@tornado.gen.coroutine
def _handle_decoded_payload(self, data):
mp_call = _metaproxy_call(self.opts, 'handle_decoded_payload')
return mp_call(self, data)
@classmethod
def _target(cls, minion_instance, opts, data, connected):
mp_call = _metaproxy_call(opts, 'target')
return mp_call(cls, minion_instance, opts, data, connected)
@classmethod
def _thread_return(cls, minion_instance, opts, data):
mp_call = _metaproxy_call(opts, 'thread_return')
return mp_call(cls, minion_instance, opts, data)
@classmethod
def _thread_multi_return(cls, minion_instance, opts, data):
mp_call = _metaproxy_call(opts, 'thread_multi_return')
return mp_call(cls, minion_instance, opts, data)
class SProxyMinion(SMinion):
'''
Create an object that has loaded all of the minion module functions,
grains, modules, returners etc. The SProxyMinion allows developers to
generate all of the salt minion functions and present them with these
functions for general use.
'''
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
'''
self.opts['grains'] = salt.loader.grains(self.opts)
self.opts['pillar'] = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
saltenv=self.opts['saltenv'],
pillarenv=self.opts.get('pillarenv'),
).compile_pillar()
if 'proxy' not in self.opts['pillar'] and 'proxy' not in self.opts:
errmsg = (
'No "proxy" configuration key found in pillar or opts '
'dictionaries for id {id}. Check your pillar/options '
'configuration and contents. Salt-proxy aborted.'
).format(id=self.opts['id'])
log.error(errmsg)
self._running = False
raise SaltSystemExit(code=salt.defaults.exitcodes.EX_GENERIC, msg=errmsg)
if 'proxy' not in self.opts:
self.opts['proxy'] = self.opts['pillar']['proxy']
# Then load the proxy module
self.proxy = salt.loader.proxy(self.opts)
self.utils = salt.loader.utils(self.opts, proxy=self.proxy)
self.functions = salt.loader.minion_mods(self.opts, utils=self.utils, notify=False, proxy=self.proxy)
self.returners = salt.loader.returners(self.opts, self.functions, proxy=self.proxy)
self.matchers = salt.loader.matchers(self.opts)
self.functions['sys.reload_modules'] = self.gen_modules
self.executors = salt.loader.executors(self.opts, self.functions, proxy=self.proxy)
fq_proxyname = self.opts['proxy']['proxytype']
# we can then sync any proxymodules down from the master
# we do a sync_all here in case proxy code was installed by
# SPM or was manually placed in /srv/salt/_modules etc.
self.functions['saltutil.sync_all'](saltenv=self.opts['saltenv'])
self.functions.pack['__proxy__'] = self.proxy
self.proxy.pack['__salt__'] = self.functions
self.proxy.pack['__ret__'] = self.returners
self.proxy.pack['__pillar__'] = self.opts['pillar']
# Reload utils as well (chicken and egg, __utils__ needs __proxy__ and __proxy__ needs __utils__
self.utils = salt.loader.utils(self.opts, proxy=self.proxy)
self.proxy.pack['__utils__'] = self.utils
# Reload all modules so all dunder variables are injected
self.proxy.reload_modules()
if ('{0}.init'.format(fq_proxyname) not in self.proxy
or '{0}.shutdown'.format(fq_proxyname) not in self.proxy):
errmsg = 'Proxymodule {0} is missing an init() or a shutdown() or both. '.format(fq_proxyname) + \
'Check your proxymodule. Salt-proxy aborted.'
log.error(errmsg)
self._running = False
raise SaltSystemExit(code=salt.defaults.exitcodes.EX_GENERIC, msg=errmsg)
self.module_executors = self.proxy.get('{0}.module_executors'.format(fq_proxyname), lambda: [])()
proxy_init_fn = self.proxy[fq_proxyname + '.init']
proxy_init_fn(self.opts)
self.opts['grains'] = salt.loader.grains(self.opts, proxy=self.proxy)
# Sync the grains here so the proxy can communicate them to the master
self.functions['saltutil.sync_grains'](saltenv='base')
self.grains_cache = self.opts['grains']
self.ready = True
|
saltstack/salt
|
salt/minion.py
|
prep_ip_port
|
python
|
def prep_ip_port(opts):
'''
parse host:port values from opts['master'] and return valid:
master: ip address or hostname as a string
master_port: (optional) master returner port as integer
e.g.:
- master: 'localhost:1234' -> {'master': 'localhost', 'master_port': 1234}
- master: '127.0.0.1:1234' -> {'master': '127.0.0.1', 'master_port' :1234}
- master: '[::1]:1234' -> {'master': '::1', 'master_port': 1234}
- master: 'fe80::a00:27ff:fedc:ba98' -> {'master': 'fe80::a00:27ff:fedc:ba98'}
'''
ret = {}
# Use given master IP if "ip_only" is set or if master_ip is an ipv6 address without
# a port specified. The is_ipv6 check returns False if brackets are used in the IP
# definition such as master: '[::1]:1234'.
if opts['master_uri_format'] == 'ip_only':
ret['master'] = ipaddress.ip_address(opts['master'])
else:
host, port = parse_host_port(opts['master'])
ret = {'master': host}
if port:
ret.update({'master_port': port})
return ret
|
parse host:port values from opts['master'] and return valid:
master: ip address or hostname as a string
master_port: (optional) master returner port as integer
e.g.:
- master: 'localhost:1234' -> {'master': 'localhost', 'master_port': 1234}
- master: '127.0.0.1:1234' -> {'master': '127.0.0.1', 'master_port' :1234}
- master: '[::1]:1234' -> {'master': '::1', 'master_port': 1234}
- master: 'fe80::a00:27ff:fedc:ba98' -> {'master': 'fe80::a00:27ff:fedc:ba98'}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/minion.py#L245-L269
|
[
"def parse_host_port(host_port):\n \"\"\"\n Takes a string argument specifying host or host:port.\n\n Returns a (hostname, port) or (ip_address, port) tuple. If no port is given,\n the second (port) element of the returned tuple will be None.\n\n host:port argument, for example, is accepted in the forms of:\n - hostname\n - hostname:1234\n - hostname.domain.tld\n - hostname.domain.tld:5678\n - [1234::5]:5678\n - 1234::5\n - 10.11.12.13:4567\n - 10.11.12.13\n \"\"\"\n host, port = None, None # default\n\n _s_ = host_port[:]\n if _s_[0] == \"[\":\n if \"]\" in host_port:\n host, _s_ = _s_.lstrip(\"[\").rsplit(\"]\", 1)\n host = ipaddress.IPv6Address(host).compressed\n if _s_[0] == \":\":\n port = int(_s_.lstrip(\":\"))\n else:\n if len(_s_) > 1:\n raise ValueError('found ambiguous \"{}\" port in \"{}\"'.format(_s_, host_port))\n else:\n if _s_.count(\":\") == 1:\n host, _hostport_separator_, port = _s_.partition(\":\")\n try:\n port = int(port)\n except ValueError as _e_:\n log.error('host_port \"%s\" port value \"%s\" is not an integer.', host_port, port)\n raise _e_\n else:\n host = _s_\n try:\n if not isinstance(host, ipaddress._BaseAddress):\n host_ip = ipaddress.ip_address(host).compressed\n host = host_ip\n except ValueError:\n log.debug('\"%s\" Not an IP address? Assuming it is a hostname.', host)\n if host != sanitize_host(host):\n log.error('bad hostname: \"%s\"', host)\n raise ValueError('bad hostname: \"{}\"'.format(host))\n\n return host, port\n"
] |
# -*- coding: utf-8 -*-
'''
Routines to set up a minion
'''
# Import python libs
from __future__ import absolute_import, print_function, with_statement, unicode_literals
import functools
import os
import sys
import copy
import time
import types
import signal
import random
import logging
import threading
import traceback
import contextlib
import multiprocessing
from random import randint, shuffle
from stat import S_IMODE
import salt.serializers.msgpack
from binascii import crc32
# Import Salt Libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt._compat import ipaddress
from salt.utils.network import parse_host_port
from salt.ext.six.moves import range
from salt.utils.zeromq import zmq, ZMQDefaultLoop, install_zmq, ZMQ_VERSION_INFO
import salt.transport.client
import salt.defaults.exitcodes
from salt.utils.ctx import RequestContext
# pylint: enable=no-name-in-module,redefined-builtin
import tornado
HAS_PSUTIL = False
try:
import salt.utils.psutil_compat as psutil
HAS_PSUTIL = True
except ImportError:
pass
HAS_RESOURCE = False
try:
import resource
HAS_RESOURCE = True
except ImportError:
pass
try:
import zmq.utils.monitor
HAS_ZMQ_MONITOR = True
except ImportError:
HAS_ZMQ_MONITOR = False
try:
import salt.utils.win_functions
HAS_WIN_FUNCTIONS = True
except ImportError:
HAS_WIN_FUNCTIONS = False
# pylint: enable=import-error
# Import salt libs
import salt
import salt.client
import salt.crypt
import salt.loader
import salt.beacons
import salt.engines
import salt.payload
import salt.pillar
import salt.syspaths
import salt.utils.args
import salt.utils.context
import salt.utils.data
import salt.utils.error
import salt.utils.event
import salt.utils.files
import salt.utils.jid
import salt.utils.minion
import salt.utils.minions
import salt.utils.network
import salt.utils.platform
import salt.utils.process
import salt.utils.schedule
import salt.utils.ssdp
import salt.utils.user
import salt.utils.zeromq
import salt.defaults.events
import salt.defaults.exitcodes
import salt.cli.daemons
import salt.log.setup
import salt.utils.dictupdate
from salt.config import DEFAULT_MINION_OPTS
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.utils.debug import enable_sigusr1_handler
from salt.utils.event import tagify
from salt.utils.odict import OrderedDict
from salt.utils.process import (default_signals,
SignalHandlingMultiprocessingProcess,
ProcessManager)
from salt.exceptions import (
CommandExecutionError,
CommandNotFoundError,
SaltInvocationError,
SaltReqTimeoutError,
SaltClientError,
SaltSystemExit,
SaltDaemonNotRunning,
SaltException,
SaltMasterUnresolvableError
)
import tornado.gen # pylint: disable=F0401
import tornado.ioloop # pylint: disable=F0401
log = logging.getLogger(__name__)
# To set up a minion:
# 1. Read in the configuration
# 2. Generate the function mapping dict
# 3. Authenticate with the master
# 4. Store the AES key
# 5. Connect to the publisher
# 6. Handle publications
def resolve_dns(opts, fallback=True):
'''
Resolves the master_ip and master_uri options
'''
ret = {}
check_dns = True
if (opts.get('file_client', 'remote') == 'local' and
not opts.get('use_master_when_local', False)):
check_dns = False
# Since salt.log is imported below, salt.utils.network needs to be imported here as well
import salt.utils.network
if check_dns is True:
try:
if opts['master'] == '':
raise SaltSystemExit
ret['master_ip'] = salt.utils.network.dns_check(
opts['master'],
int(opts['master_port']),
True,
opts['ipv6'],
attempt_connect=False)
except SaltClientError:
retry_dns_count = opts.get('retry_dns_count', None)
if opts['retry_dns']:
while True:
if retry_dns_count is not None:
if retry_dns_count == 0:
raise SaltMasterUnresolvableError
retry_dns_count -= 1
import salt.log
msg = ('Master hostname: \'{0}\' not found or not responsive. '
'Retrying in {1} seconds').format(opts['master'], opts['retry_dns'])
if salt.log.setup.is_console_configured():
log.error(msg)
else:
print('WARNING: {0}'.format(msg))
time.sleep(opts['retry_dns'])
try:
ret['master_ip'] = salt.utils.network.dns_check(
opts['master'],
int(opts['master_port']),
True,
opts['ipv6'],
attempt_connect=False)
break
except SaltClientError:
pass
else:
if fallback:
ret['master_ip'] = '127.0.0.1'
else:
raise
except SaltSystemExit:
unknown_str = 'unknown address'
master = opts.get('master', unknown_str)
if master == '':
master = unknown_str
if opts.get('__role') == 'syndic':
err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \
'Set \'syndic_master\' value in minion config.'.format(master)
else:
err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \
'Set \'master\' value in minion config.'.format(master)
log.error(err)
raise SaltSystemExit(code=42, msg=err)
else:
ret['master_ip'] = '127.0.0.1'
if 'master_ip' in ret and 'master_ip' in opts:
if ret['master_ip'] != opts['master_ip']:
log.warning(
'Master ip address changed from %s to %s',
opts['master_ip'], ret['master_ip']
)
if opts['source_interface_name']:
log.trace('Custom source interface required: %s', opts['source_interface_name'])
interfaces = salt.utils.network.interfaces()
log.trace('The following interfaces are available on this Minion:')
log.trace(interfaces)
if opts['source_interface_name'] in interfaces:
if interfaces[opts['source_interface_name']]['up']:
addrs = interfaces[opts['source_interface_name']]['inet'] if not opts['ipv6'] else\
interfaces[opts['source_interface_name']]['inet6']
ret['source_ip'] = addrs[0]['address']
log.debug('Using %s as source IP address', ret['source_ip'])
else:
log.warning('The interface %s is down so it cannot be used as source to connect to the Master',
opts['source_interface_name'])
else:
log.warning('%s is not a valid interface. Ignoring.', opts['source_interface_name'])
elif opts['source_address']:
ret['source_ip'] = salt.utils.network.dns_check(
opts['source_address'],
int(opts['source_ret_port']),
True,
opts['ipv6'],
attempt_connect=False)
log.debug('Using %s as source IP address', ret['source_ip'])
if opts['source_ret_port']:
ret['source_ret_port'] = int(opts['source_ret_port'])
log.debug('Using %d as source port for the ret server', ret['source_ret_port'])
if opts['source_publish_port']:
ret['source_publish_port'] = int(opts['source_publish_port'])
log.debug('Using %d as source port for the master pub', ret['source_publish_port'])
ret['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=ret['master_ip'], port=opts['master_port'])
log.debug('Master URI: %s', ret['master_uri'])
return ret
def get_proc_dir(cachedir, **kwargs):
'''
Given the cache directory, return the directory that process data is
stored in, creating it if it doesn't exist.
The following optional Keyword Arguments are handled:
mode: which is anything os.makedir would accept as mode.
uid: the uid to set, if not set, or it is None or -1 no changes are
made. Same applies if the directory is already owned by this
uid. Must be int. Works only on unix/unix like systems.
gid: the gid to set, if not set, or it is None or -1 no changes are
made. Same applies if the directory is already owned by this
gid. Must be int. Works only on unix/unix like systems.
'''
fn_ = os.path.join(cachedir, 'proc')
mode = kwargs.pop('mode', None)
if mode is None:
mode = {}
else:
mode = {'mode': mode}
if not os.path.isdir(fn_):
# proc_dir is not present, create it with mode settings
os.makedirs(fn_, **mode)
d_stat = os.stat(fn_)
# if mode is not an empty dict then we have an explicit
# dir mode. So lets check if mode needs to be changed.
if mode:
mode_part = S_IMODE(d_stat.st_mode)
if mode_part != mode['mode']:
os.chmod(fn_, (d_stat.st_mode ^ mode_part) | mode['mode'])
if hasattr(os, 'chown'):
# only on unix/unix like systems
uid = kwargs.pop('uid', -1)
gid = kwargs.pop('gid', -1)
# if uid and gid are both -1 then go ahead with
# no changes at all
if (d_stat.st_uid != uid or d_stat.st_gid != gid) and \
[i for i in (uid, gid) if i != -1]:
os.chown(fn_, uid, gid)
return fn_
def load_args_and_kwargs(func, args, data=None, ignore_invalid=False):
'''
Detect the args and kwargs that need to be passed to a function call, and
check them against what was passed.
'''
argspec = salt.utils.args.get_function_argspec(func)
_args = []
_kwargs = {}
invalid_kwargs = []
for arg in args:
if isinstance(arg, dict) and arg.pop('__kwarg__', False) is True:
# if the arg is a dict with __kwarg__ == True, then its a kwarg
for key, val in six.iteritems(arg):
if argspec.keywords or key in argspec.args:
# Function supports **kwargs or is a positional argument to
# the function.
_kwargs[key] = val
else:
# **kwargs not in argspec and parsed argument name not in
# list of positional arguments. This keyword argument is
# invalid.
invalid_kwargs.append('{0}={1}'.format(key, val))
continue
else:
string_kwarg = salt.utils.args.parse_input([arg], condition=False)[1] # pylint: disable=W0632
if string_kwarg:
if argspec.keywords or next(six.iterkeys(string_kwarg)) in argspec.args:
# Function supports **kwargs or is a positional argument to
# the function.
_kwargs.update(string_kwarg)
else:
# **kwargs not in argspec and parsed argument name not in
# list of positional arguments. This keyword argument is
# invalid.
for key, val in six.iteritems(string_kwarg):
invalid_kwargs.append('{0}={1}'.format(key, val))
else:
_args.append(arg)
if invalid_kwargs and not ignore_invalid:
salt.utils.args.invalid_kwargs(invalid_kwargs)
if argspec.keywords and isinstance(data, dict):
# this function accepts **kwargs, pack in the publish data
for key, val in six.iteritems(data):
_kwargs['__pub_{0}'.format(key)] = val
return _args, _kwargs
def eval_master_func(opts):
'''
Evaluate master function if master type is 'func'
and save it result in opts['master']
'''
if '__master_func_evaluated' not in opts:
# split module and function and try loading the module
mod_fun = opts['master']
mod, fun = mod_fun.split('.')
try:
master_mod = salt.loader.raw_mod(opts, mod, fun)
if not master_mod:
raise KeyError
# we take whatever the module returns as master address
opts['master'] = master_mod[mod_fun]()
# Check for valid types
if not isinstance(opts['master'], (six.string_types, list)):
raise TypeError
opts['__master_func_evaluated'] = True
except KeyError:
log.error('Failed to load module %s', mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except TypeError:
log.error('%s returned from %s is not a string', opts['master'], mod_fun)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated master from module: %s', mod_fun)
def master_event(type, master=None):
'''
Centralized master event function which will return event type based on event_map
'''
event_map = {'connected': '__master_connected',
'disconnected': '__master_disconnected',
'failback': '__master_failback',
'alive': '__master_alive'}
if type == 'alive' and master is not None:
return '{0}_{1}'.format(event_map.get(type), master)
return event_map.get(type, None)
def service_name():
'''
Return the proper service name based on platform
'''
return 'salt_minion' if 'bsd' in sys.platform else 'salt-minion'
class MinionBase(object):
def __init__(self, opts):
self.opts = opts
@staticmethod
def process_schedule(minion, loop_interval):
try:
if hasattr(minion, 'schedule'):
minion.schedule.eval()
else:
log.error('Minion scheduler not initialized. Scheduled jobs will not be run.')
return
# Check if scheduler requires lower loop interval than
# the loop_interval setting
if minion.schedule.loop_interval < loop_interval:
loop_interval = minion.schedule.loop_interval
log.debug(
'Overriding loop_interval because of scheduled jobs.'
)
except Exception as exc:
log.error('Exception %s occurred in scheduled job', exc)
return loop_interval
def process_beacons(self, functions):
'''
Evaluate all of the configured beacons, grab the config again in case
the pillar or grains changed
'''
if 'config.merge' in functions:
b_conf = functions['config.merge']('beacons', self.opts['beacons'], omit_opts=True)
if b_conf:
return self.beacons.process(b_conf, self.opts['grains']) # pylint: disable=no-member
return []
@tornado.gen.coroutine
def eval_master(self,
opts,
timeout=60,
safe=True,
failed=False,
failback=False):
'''
Evaluates and returns a tuple of the current master address and the pub_channel.
In standard mode, just creates a pub_channel with the given master address.
With master_type=func evaluates the current master address from the given
module and then creates a pub_channel.
With master_type=failover takes the list of masters and loops through them.
The first one that allows the minion to create a pub_channel is then
returned. If this function is called outside the minions initialization
phase (for example from the minions main event-loop when a master connection
loss was detected), 'failed' should be set to True. The current
(possibly failed) master will then be removed from the list of masters.
'''
# return early if we are not connecting to a master
if opts['master_type'] == 'disable':
log.warning('Master is set to disable, skipping connection')
self.connected = False
raise tornado.gen.Return((None, None))
# Run masters discovery over SSDP. This may modify the whole configuration,
# depending of the networking and sets of masters.
# if we are using multimaster, discovery can only happen at start time
# because MinionManager handles it. by eval_master time the minion doesn't
# know about other siblings currently running
if isinstance(self.opts['discovery'], dict) and not self.opts['discovery'].get('multimaster'):
self._discover_masters()
# check if master_type was altered from its default
if opts['master_type'] != 'str' and opts['__role'] != 'syndic':
# check for a valid keyword
if opts['master_type'] == 'func':
eval_master_func(opts)
# if failover or distributed is set, master has to be of type list
elif opts['master_type'] in ('failover', 'distributed'):
if isinstance(opts['master'], list):
log.info(
'Got list of available master addresses: %s',
opts['master']
)
if opts['master_type'] == 'distributed':
master_len = len(opts['master'])
if master_len > 1:
secondary_masters = opts['master'][1:]
master_idx = crc32(opts['id']) % master_len
try:
preferred_masters = opts['master']
preferred_masters[0] = opts['master'][master_idx]
preferred_masters[1:] = [m for m in opts['master'] if m != preferred_masters[0]]
opts['master'] = preferred_masters
log.info('Distributed to the master at \'%s\'.', opts['master'][0])
except (KeyError, AttributeError, TypeError):
log.warning('Failed to distribute to a specific master.')
else:
log.warning('master_type = distributed needs more than 1 master.')
if opts['master_shuffle']:
log.warning(
'Use of \'master_shuffle\' detected. \'master_shuffle\' is deprecated in favor '
'of \'random_master\'. Please update your minion config file.'
)
opts['random_master'] = opts['master_shuffle']
opts['auth_tries'] = 0
if opts['master_failback'] and opts['master_failback_interval'] == 0:
opts['master_failback_interval'] = opts['master_alive_interval']
# if opts['master'] is a str and we have never created opts['master_list']
elif isinstance(opts['master'], six.string_types) and ('master_list' not in opts):
# We have a string, but a list was what was intended. Convert.
# See issue 23611 for details
opts['master'] = [opts['master']]
elif opts['__role'] == 'syndic':
log.info('Syndic setting master_syndic to \'%s\'', opts['master'])
# if failed=True, the minion was previously connected
# we're probably called from the minions main-event-loop
# because a master connection loss was detected. remove
# the possibly failed master from the list of masters.
elif failed:
if failback:
# failback list of masters to original config
opts['master'] = opts['master_list']
else:
log.info(
'Moving possibly failed master %s to the end of '
'the list of masters', opts['master']
)
if opts['master'] in opts['local_masters']:
# create new list of master with the possibly failed
# one moved to the end
failed_master = opts['master']
opts['master'] = [x for x in opts['local_masters'] if opts['master'] != x]
opts['master'].append(failed_master)
else:
opts['master'] = opts['master_list']
else:
msg = ('master_type set to \'failover\' but \'master\' '
'is not of type list but of type '
'{0}'.format(type(opts['master'])))
log.error(msg)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# If failover is set, minion have to failover on DNS errors instead of retry DNS resolve.
# See issue 21082 for details
if opts['retry_dns'] and opts['master_type'] == 'failover':
msg = ('\'master_type\' set to \'failover\' but \'retry_dns\' is not 0. '
'Setting \'retry_dns\' to 0 to failover to the next master on DNS errors.')
log.critical(msg)
opts['retry_dns'] = 0
else:
msg = ('Invalid keyword \'{0}\' for variable '
'\'master_type\''.format(opts['master_type']))
log.error(msg)
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
# FIXME: if SMinion don't define io_loop, it can't switch master see #29088
# Specify kwargs for the channel factory so that SMinion doesn't need to define an io_loop
# (The channel factories will set a default if the kwarg isn't passed)
factory_kwargs = {'timeout': timeout, 'safe': safe}
if getattr(self, 'io_loop', None):
factory_kwargs['io_loop'] = self.io_loop # pylint: disable=no-member
tries = opts.get('master_tries', 1)
attempts = 0
# if we have a list of masters, loop through them and be
# happy with the first one that allows us to connect
if isinstance(opts['master'], list):
conn = False
last_exc = None
opts['master_uri_list'] = []
opts['local_masters'] = copy.copy(opts['master'])
# shuffle the masters and then loop through them
if opts['random_master']:
# master_failback is only used when master_type is set to failover
if opts['master_type'] == 'failover' and opts['master_failback']:
secondary_masters = opts['local_masters'][1:]
shuffle(secondary_masters)
opts['local_masters'][1:] = secondary_masters
else:
shuffle(opts['local_masters'])
# This sits outside of the connection loop below because it needs to set
# up a list of master URIs regardless of which masters are available
# to connect _to_. This is primarily used for masterless mode, when
# we need a list of master URIs to fire calls back to.
for master in opts['local_masters']:
opts['master'] = master
opts.update(prep_ip_port(opts))
opts['master_uri_list'].append(resolve_dns(opts)['master_uri'])
while True:
if attempts != 0:
# Give up a little time between connection attempts
# to allow the IOLoop to run any other scheduled tasks.
yield tornado.gen.sleep(opts['acceptance_wait_time'])
attempts += 1
if tries > 0:
log.debug(
'Connecting to master. Attempt %s of %s',
attempts, tries
)
else:
log.debug(
'Connecting to master. Attempt %s (infinite attempts)',
attempts
)
for master in opts['local_masters']:
opts['master'] = master
opts.update(prep_ip_port(opts))
opts.update(resolve_dns(opts))
# on first run, update self.opts with the whole master list
# to enable a minion to re-use old masters if they get fixed
if 'master_list' not in opts:
opts['master_list'] = copy.copy(opts['local_masters'])
self.opts = opts
pub_channel = salt.transport.client.AsyncPubChannel.factory(opts, **factory_kwargs)
try:
yield pub_channel.connect()
conn = True
break
except SaltClientError as exc:
last_exc = exc
if exc.strerror.startswith('Could not access'):
msg = (
'Failed to initiate connection with Master '
'%s: check ownership/permissions. Error '
'message: %s', opts['master'], exc
)
else:
msg = ('Master %s could not be reached, trying next '
'next master (if any)', opts['master'])
log.info(msg)
continue
if not conn:
if attempts == tries:
# Exhausted all attempts. Return exception.
self.connected = False
self.opts['master'] = copy.copy(self.opts['local_masters'])
log.error(
'No master could be reached or all masters '
'denied the minion\'s connection attempt.'
)
# If the code reaches this point, 'last_exc'
# should already be set.
raise last_exc # pylint: disable=E0702
else:
self.tok = pub_channel.auth.gen_token(b'salt')
self.connected = True
raise tornado.gen.Return((opts['master'], pub_channel))
# single master sign in
else:
if opts['random_master']:
log.warning('random_master is True but there is only one master specified. Ignoring.')
while True:
if attempts != 0:
# Give up a little time between connection attempts
# to allow the IOLoop to run any other scheduled tasks.
yield tornado.gen.sleep(opts['acceptance_wait_time'])
attempts += 1
if tries > 0:
log.debug(
'Connecting to master. Attempt %s of %s',
attempts, tries
)
else:
log.debug(
'Connecting to master. Attempt %s (infinite attempts)',
attempts
)
opts.update(prep_ip_port(opts))
opts.update(resolve_dns(opts))
try:
if self.opts['transport'] == 'detect':
self.opts['detect_mode'] = True
for trans in ('zeromq', 'tcp'):
if trans == 'zeromq' and not zmq:
continue
self.opts['transport'] = trans
pub_channel = salt.transport.client.AsyncPubChannel.factory(self.opts, **factory_kwargs)
yield pub_channel.connect()
if not pub_channel.auth.authenticated:
continue
del self.opts['detect_mode']
break
else:
pub_channel = salt.transport.client.AsyncPubChannel.factory(self.opts, **factory_kwargs)
yield pub_channel.connect()
self.tok = pub_channel.auth.gen_token(b'salt')
self.connected = True
raise tornado.gen.Return((opts['master'], pub_channel))
except SaltClientError as exc:
if attempts == tries:
# Exhausted all attempts. Return exception.
self.connected = False
raise exc
def _discover_masters(self):
'''
Discover master(s) and decide where to connect, if SSDP is around.
This modifies the configuration on the fly.
:return:
'''
if self.opts['master'] == DEFAULT_MINION_OPTS['master'] and self.opts['discovery'] is not False:
master_discovery_client = salt.utils.ssdp.SSDPDiscoveryClient()
masters = {}
for att in range(self.opts['discovery'].get('attempts', 3)):
try:
att += 1
log.info('Attempting %s time(s) to discover masters', att)
masters.update(master_discovery_client.discover())
if not masters:
time.sleep(self.opts['discovery'].get('pause', 5))
else:
break
except Exception as err:
log.error('SSDP discovery failure: %s', err)
break
if masters:
policy = self.opts.get('discovery', {}).get('match', 'any')
if policy not in ['any', 'all']:
log.error('SSDP configuration matcher failure: unknown value "%s". '
'Should be "any" or "all"', policy)
return
mapping = self.opts['discovery'].get('mapping', {})
discovered = []
for addr, mappings in masters.items():
for proto_data in mappings:
cnt = len([key for key, value in mapping.items()
if proto_data.get('mapping', {}).get(key) == value])
if policy == 'any' and bool(cnt) or cnt == len(mapping):
if self.opts['discovery'].get('multimaster'):
discovered.append(proto_data['master'])
else:
self.opts['master'] = proto_data['master']
return
self.opts['master'] = discovered
def _return_retry_timer(self):
'''
Based on the minion configuration, either return a randomized timer or
just return the value of the return_retry_timer.
'''
msg = 'Minion return retry timer set to %s seconds'
if self.opts.get('return_retry_timer_max'):
try:
random_retry = randint(self.opts['return_retry_timer'], self.opts['return_retry_timer_max'])
retry_msg = msg % random_retry
log.debug('%s (randomized)', msg % random_retry)
return random_retry
except ValueError:
# Catch wiseguys using negative integers here
log.error(
'Invalid value (return_retry_timer: %s or '
'return_retry_timer_max: %s). Both must be positive '
'integers.',
self.opts['return_retry_timer'],
self.opts['return_retry_timer_max'],
)
log.debug(msg, DEFAULT_MINION_OPTS['return_retry_timer'])
return DEFAULT_MINION_OPTS['return_retry_timer']
else:
log.debug(msg, self.opts.get('return_retry_timer'))
return self.opts.get('return_retry_timer')
class SMinion(MinionBase):
'''
Create an object that has loaded all of the minion module functions,
grains, modules, returners etc. The SMinion allows developers to
generate all of the salt minion functions and present them with these
functions for general use.
'''
def __init__(self, opts):
# Late setup of the opts grains, so we can log from the grains module
import salt.loader
opts['grains'] = salt.loader.grains(opts)
super(SMinion, self).__init__(opts)
# run ssdp discovery if necessary
self._discover_masters()
# Clean out the proc directory (default /var/cache/salt/minion/proc)
if (self.opts.get('file_client', 'remote') == 'remote'
or self.opts.get('use_master_when_local', False)):
install_zmq()
io_loop = ZMQDefaultLoop.current()
io_loop.run_sync(
lambda: self.eval_master(self.opts, failed=True)
)
self.gen_modules(initial_load=True)
# If configured, cache pillar data on the minion
if self.opts['file_client'] == 'remote' and self.opts.get('minion_pillar_cache', False):
import salt.utils.yaml
pdir = os.path.join(self.opts['cachedir'], 'pillar')
if not os.path.isdir(pdir):
os.makedirs(pdir, 0o700)
ptop = os.path.join(pdir, 'top.sls')
if self.opts['saltenv'] is not None:
penv = self.opts['saltenv']
else:
penv = 'base'
cache_top = {penv: {self.opts['id']: ['cache']}}
with salt.utils.files.fopen(ptop, 'wb') as fp_:
salt.utils.yaml.safe_dump(cache_top, fp_)
os.chmod(ptop, 0o600)
cache_sls = os.path.join(pdir, 'cache.sls')
with salt.utils.files.fopen(cache_sls, 'wb') as fp_:
salt.utils.yaml.safe_dump(self.opts['pillar'], fp_)
os.chmod(cache_sls, 0o600)
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
'''
self.opts['pillar'] = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillarenv=self.opts.get('pillarenv'),
).compile_pillar()
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, utils=self.utils)
self.serializers = salt.loader.serializers(self.opts)
self.returners = salt.loader.returners(self.opts, self.functions)
self.proxy = salt.loader.proxy(self.opts, self.functions, self.returners, None)
# TODO: remove
self.function_errors = {} # Keep the funcs clean
self.states = salt.loader.states(self.opts,
self.functions,
self.utils,
self.serializers)
self.rend = salt.loader.render(self.opts, self.functions)
# self.matcher = Matcher(self.opts, self.functions)
self.matchers = salt.loader.matchers(self.opts)
self.functions['sys.reload_modules'] = self.gen_modules
self.executors = salt.loader.executors(self.opts)
class MasterMinion(object):
'''
Create a fully loaded minion function object for generic use on the
master. What makes this class different is that the pillar is
omitted, otherwise everything else is loaded cleanly.
'''
def __init__(
self,
opts,
returners=True,
states=True,
rend=True,
matcher=True,
whitelist=None,
ignore_config_errors=True):
self.opts = salt.config.minion_config(
opts['conf_file'],
ignore_config_errors=ignore_config_errors,
role='master'
)
self.opts.update(opts)
self.whitelist = whitelist
self.opts['grains'] = salt.loader.grains(opts)
self.opts['pillar'] = {}
self.mk_returners = returners
self.mk_states = states
self.mk_rend = rend
self.mk_matcher = matcher
self.gen_modules(initial_load=True)
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
'''
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(
self.opts,
utils=self.utils,
whitelist=self.whitelist,
initial_load=initial_load)
self.serializers = salt.loader.serializers(self.opts)
if self.mk_returners:
self.returners = salt.loader.returners(self.opts, self.functions)
if self.mk_states:
self.states = salt.loader.states(self.opts,
self.functions,
self.utils,
self.serializers)
if self.mk_rend:
self.rend = salt.loader.render(self.opts, self.functions)
if self.mk_matcher:
self.matchers = salt.loader.matchers(self.opts)
self.functions['sys.reload_modules'] = self.gen_modules
class MinionManager(MinionBase):
'''
Create a multi minion interface, this creates as many minions as are
defined in the master option and binds each minion object to a respective
master.
'''
def __init__(self, opts):
super(MinionManager, self).__init__(opts)
self.auth_wait = self.opts['acceptance_wait_time']
self.max_auth_wait = self.opts['acceptance_wait_time_max']
self.minions = []
self.jid_queue = []
install_zmq()
self.io_loop = ZMQDefaultLoop.current()
self.process_manager = ProcessManager(name='MultiMinionProcessManager')
self.io_loop.spawn_callback(self.process_manager.run, **{'asynchronous': True}) # Tornado backward compat
def __del__(self):
self.destroy()
def _bind(self):
# start up the event publisher, so we can see events during startup
self.event_publisher = salt.utils.event.AsyncEventPublisher(
self.opts,
io_loop=self.io_loop,
)
self.event = salt.utils.event.get_event('minion', opts=self.opts, io_loop=self.io_loop)
self.event.subscribe('')
self.event.set_event_handler(self.handle_event)
@tornado.gen.coroutine
def handle_event(self, package):
yield [minion.handle_event(package) for minion in self.minions]
def _create_minion_object(self, opts, timeout, safe,
io_loop=None, loaded_base_name=None,
jid_queue=None):
'''
Helper function to return the correct type of object
'''
return Minion(opts,
timeout,
safe,
io_loop=io_loop,
loaded_base_name=loaded_base_name,
jid_queue=jid_queue)
def _check_minions(self):
'''
Check the size of self.minions and raise an error if it's empty
'''
if not self.minions:
err = ('Minion unable to successfully connect to '
'a Salt Master.')
log.error(err)
def _spawn_minions(self, timeout=60):
'''
Spawn all the coroutines which will sign in to masters
'''
# Run masters discovery over SSDP. This may modify the whole configuration,
# depending of the networking and sets of masters. If match is 'any' we let
# eval_master handle the discovery instead so disconnections can also handle
# discovery
if isinstance(self.opts['discovery'], dict) and self.opts['discovery'].get('multimaster'):
self._discover_masters()
masters = self.opts['master']
if (self.opts['master_type'] in ('failover', 'distributed')) or not isinstance(self.opts['master'], list):
masters = [masters]
for master in masters:
s_opts = copy.deepcopy(self.opts)
s_opts['master'] = master
s_opts['multimaster'] = True
minion = self._create_minion_object(s_opts,
s_opts['auth_timeout'],
False,
io_loop=self.io_loop,
loaded_base_name='salt.loader.{0}'.format(s_opts['master']),
jid_queue=self.jid_queue)
self.io_loop.spawn_callback(self._connect_minion, minion)
self.io_loop.call_later(timeout, self._check_minions)
@tornado.gen.coroutine
def _connect_minion(self, minion):
'''
Create a minion, and asynchronously connect it to a master
'''
auth_wait = minion.opts['acceptance_wait_time']
failed = False
while True:
if failed:
if auth_wait < self.max_auth_wait:
auth_wait += self.auth_wait
log.debug(
"sleeping before reconnect attempt to %s [%d/%d]",
minion.opts['master'],
auth_wait,
self.max_auth_wait,
)
yield tornado.gen.sleep(auth_wait) # TODO: log?
try:
if minion.opts.get('beacons_before_connect', False):
minion.setup_beacons(before_connect=True)
if minion.opts.get('scheduler_before_connect', False):
minion.setup_scheduler(before_connect=True)
yield minion.connect_master(failed=failed)
minion.tune_in(start=False)
self.minions.append(minion)
break
except SaltClientError as exc:
failed = True
log.error(
'Error while bringing up minion for multi-master. Is '
'master at %s responding?', minion.opts['master']
)
except SaltMasterUnresolvableError:
err = 'Master address: \'{0}\' could not be resolved. Invalid or unresolveable address. ' \
'Set \'master\' value in minion config.'.format(minion.opts['master'])
log.error(err)
break
except Exception as e:
failed = True
log.critical(
'Unexpected error while connecting to %s',
minion.opts['master'], exc_info=True
)
# Multi Master Tune In
def tune_in(self):
'''
Bind to the masters
This loop will attempt to create connections to masters it hasn't connected
to yet, but once the initial connection is made it is up to ZMQ to do the
reconnect (don't know of an API to get the state here in salt)
'''
self._bind()
# Fire off all the minion coroutines
self._spawn_minions()
# serve forever!
self.io_loop.start()
@property
def restart(self):
for minion in self.minions:
if minion.restart:
return True
return False
def stop(self, signum):
for minion in self.minions:
minion.process_manager.stop_restarting()
minion.process_manager.send_signal_to_processes(signum)
# kill any remaining processes
minion.process_manager.kill_children()
minion.destroy()
def destroy(self):
for minion in self.minions:
minion.destroy()
class Minion(MinionBase):
'''
This class instantiates a minion, runs connections for a minion,
and loads all of the functions into the minion
'''
def __init__(self, opts, timeout=60, safe=True, loaded_base_name=None, io_loop=None, jid_queue=None): # pylint: disable=W0231
'''
Pass in the options dict
'''
# this means that the parent class doesn't know *which* master we connect to
super(Minion, self).__init__(opts)
self.timeout = timeout
self.safe = safe
self._running = None
self.win_proc = []
self.loaded_base_name = loaded_base_name
self.connected = False
self.restart = False
# Flag meaning minion has finished initialization including first connect to the master.
# True means the Minion is fully functional and ready to handle events.
self.ready = False
self.jid_queue = [] if jid_queue is None else jid_queue
self.periodic_callbacks = {}
if io_loop is None:
install_zmq()
self.io_loop = ZMQDefaultLoop.current()
else:
self.io_loop = io_loop
# Warn if ZMQ < 3.2
if zmq:
if ZMQ_VERSION_INFO < (3, 2):
log.warning(
'You have a version of ZMQ less than ZMQ 3.2! There are '
'known connection keep-alive issues with ZMQ < 3.2 which '
'may result in loss of contact with minions. Please '
'upgrade your ZMQ!'
)
# Late setup of the opts grains, so we can log from the grains
# module. If this is a proxy, however, we need to init the proxymodule
# before we can get the grains. We do this for proxies in the
# post_master_init
if not salt.utils.platform.is_proxy():
self.opts['grains'] = salt.loader.grains(opts)
else:
if self.opts.get('beacons_before_connect', False):
log.warning(
'\'beacons_before_connect\' is not supported '
'for proxy minions. Setting to False'
)
self.opts['beacons_before_connect'] = False
if self.opts.get('scheduler_before_connect', False):
log.warning(
'\'scheduler_before_connect\' is not supported '
'for proxy minions. Setting to False'
)
self.opts['scheduler_before_connect'] = False
log.info('Creating minion process manager')
if self.opts['random_startup_delay']:
sleep_time = random.randint(0, self.opts['random_startup_delay'])
log.info(
'Minion sleeping for %s seconds due to configured '
'startup_delay between 0 and %s seconds',
sleep_time, self.opts['random_startup_delay']
)
time.sleep(sleep_time)
self.process_manager = ProcessManager(name='MinionProcessManager')
self.io_loop.spawn_callback(self.process_manager.run, **{'asynchronous': True})
# We don't have the proxy setup yet, so we can't start engines
# Engines need to be able to access __proxy__
if not salt.utils.platform.is_proxy():
self.io_loop.spawn_callback(salt.engines.start_engines, self.opts,
self.process_manager)
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, self._handle_signals)
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGTERM, self._handle_signals)
def _handle_signals(self, signum, sigframe): # pylint: disable=unused-argument
self._running = False
# escalate the signals to the process manager
self.process_manager.stop_restarting()
self.process_manager.send_signal_to_processes(signum)
# kill any remaining processes
self.process_manager.kill_children()
time.sleep(1)
sys.exit(0)
def sync_connect_master(self, timeout=None, failed=False):
'''
Block until we are connected to a master
'''
self._sync_connect_master_success = False
log.debug("sync_connect_master")
def on_connect_master_future_done(future):
self._sync_connect_master_success = True
self.io_loop.stop()
self._connect_master_future = self.connect_master(failed=failed)
# finish connecting to master
self._connect_master_future.add_done_callback(on_connect_master_future_done)
if timeout:
self.io_loop.call_later(timeout, self.io_loop.stop)
try:
self.io_loop.start()
except KeyboardInterrupt:
self.destroy()
# I made the following 3 line oddity to preserve traceback.
# Please read PR #23978 before changing, hopefully avoiding regressions.
# Good luck, we're all counting on you. Thanks.
if self._connect_master_future.done():
future_exception = self._connect_master_future.exception()
if future_exception:
# This needs to be re-raised to preserve restart_on_error behavior.
raise six.reraise(*future_exception)
if timeout and self._sync_connect_master_success is False:
raise SaltDaemonNotRunning('Failed to connect to the salt-master')
@tornado.gen.coroutine
def connect_master(self, failed=False):
'''
Return a future which will complete when you are connected to a master
'''
master, self.pub_channel = yield self.eval_master(self.opts, self.timeout, self.safe, failed)
yield self._post_master_init(master)
# TODO: better name...
@tornado.gen.coroutine
def _post_master_init(self, master):
'''
Function to finish init after connecting to a master
This is primarily loading modules, pillars, etc. (since they need
to know which master they connected to)
If this function is changed, please check ProxyMinion._post_master_init
to see if those changes need to be propagated.
Minions and ProxyMinions need significantly different post master setups,
which is why the differences are not factored out into separate helper
functions.
'''
if self.connected:
self.opts['master'] = master
# Initialize pillar before loader to make pillar accessible in modules
async_pillar = salt.pillar.get_async_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillarenv=self.opts.get('pillarenv')
)
self.opts['pillar'] = yield async_pillar.compile_pillar()
async_pillar.destroy()
if not self.ready:
self._setup_core()
elif self.connected and self.opts['pillar']:
# The pillar has changed due to the connection to the master.
# Reload the functions so that they can use the new pillar data.
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
if hasattr(self, 'schedule'):
self.schedule.functions = self.functions
self.schedule.returners = self.returners
if not hasattr(self, 'schedule'):
self.schedule = salt.utils.schedule.Schedule(
self.opts,
self.functions,
self.returners,
cleanup=[master_event(type='alive')])
# add default scheduling jobs to the minions scheduler
if self.opts['mine_enabled'] and 'mine.update' in self.functions:
self.schedule.add_job({
'__mine_interval':
{
'function': 'mine.update',
'minutes': self.opts['mine_interval'],
'jid_include': True,
'maxrunning': 2,
'run_on_start': True,
'return_job': self.opts.get('mine_return_job', False)
}
}, persist=True)
log.info('Added mine.update to scheduler')
else:
self.schedule.delete_job('__mine_interval', persist=True)
# add master_alive job if enabled
if (self.opts['transport'] != 'tcp' and
self.opts['master_alive_interval'] > 0 and
self.connected):
self.schedule.add_job({
master_event(type='alive', master=self.opts['master']):
{
'function': 'status.master',
'seconds': self.opts['master_alive_interval'],
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master'],
'connected': True}
}
}, persist=True)
if self.opts['master_failback'] and \
'master_list' in self.opts and \
self.opts['master'] != self.opts['master_list'][0]:
self.schedule.add_job({
master_event(type='failback'):
{
'function': 'status.ping_master',
'seconds': self.opts['master_failback_interval'],
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master_list'][0]}
}
}, persist=True)
else:
self.schedule.delete_job(master_event(type='failback'), persist=True)
else:
self.schedule.delete_job(master_event(type='alive', master=self.opts['master']), persist=True)
self.schedule.delete_job(master_event(type='failback'), persist=True)
def _prep_mod_opts(self):
'''
Returns a copy of the opts with key bits stripped out
'''
mod_opts = {}
for key, val in six.iteritems(self.opts):
if key == 'logger':
continue
mod_opts[key] = val
return mod_opts
def _load_modules(self, force_refresh=False, notify=False, grains=None, opts=None):
'''
Return the functions and the returners loaded up from the loader
module
'''
opt_in = True
if not opts:
opts = self.opts
opt_in = False
# if this is a *nix system AND modules_max_memory is set, lets enforce
# a memory limit on module imports
# this feature ONLY works on *nix like OSs (resource module doesn't work on windows)
modules_max_memory = False
if opts.get('modules_max_memory', -1) > 0 and HAS_PSUTIL and HAS_RESOURCE:
log.debug(
'modules_max_memory set, enforcing a maximum of %s',
opts['modules_max_memory']
)
modules_max_memory = True
old_mem_limit = resource.getrlimit(resource.RLIMIT_AS)
rss, vms = psutil.Process(os.getpid()).memory_info()[:2]
mem_limit = rss + vms + opts['modules_max_memory']
resource.setrlimit(resource.RLIMIT_AS, (mem_limit, mem_limit))
elif opts.get('modules_max_memory', -1) > 0:
if not HAS_PSUTIL:
log.error('Unable to enforce modules_max_memory because psutil is missing')
if not HAS_RESOURCE:
log.error('Unable to enforce modules_max_memory because resource is missing')
# This might be a proxy minion
if hasattr(self, 'proxy'):
proxy = self.proxy
else:
proxy = None
if grains is None:
opts['grains'] = salt.loader.grains(opts, force_refresh, proxy=proxy)
self.utils = salt.loader.utils(opts, proxy=proxy)
if opts.get('multimaster', False):
s_opts = copy.deepcopy(opts)
functions = salt.loader.minion_mods(s_opts, utils=self.utils, proxy=proxy,
loaded_base_name=self.loaded_base_name, notify=notify)
else:
functions = salt.loader.minion_mods(opts, utils=self.utils, notify=notify, proxy=proxy)
returners = salt.loader.returners(opts, functions, proxy=proxy)
errors = {}
if '_errors' in functions:
errors = functions['_errors']
functions.pop('_errors')
# we're done, reset the limits!
if modules_max_memory is True:
resource.setrlimit(resource.RLIMIT_AS, old_mem_limit)
executors = salt.loader.executors(opts, functions, proxy=proxy)
if opt_in:
self.opts = opts
return functions, returners, errors, executors
def _send_req_sync(self, load, timeout):
if self.opts['minion_sign_messages']:
log.trace('Signing event to be published onto the bus.')
minion_privkey_path = os.path.join(self.opts['pki_dir'], 'minion.pem')
sig = salt.crypt.sign_message(minion_privkey_path, salt.serializers.msgpack.serialize(load))
load['sig'] = sig
channel = salt.transport.client.ReqChannel.factory(self.opts)
try:
return channel.send(load, timeout=timeout)
finally:
channel.close()
@tornado.gen.coroutine
def _send_req_async(self, load, timeout):
if self.opts['minion_sign_messages']:
log.trace('Signing event to be published onto the bus.')
minion_privkey_path = os.path.join(self.opts['pki_dir'], 'minion.pem')
sig = salt.crypt.sign_message(minion_privkey_path, salt.serializers.msgpack.serialize(load))
load['sig'] = sig
channel = salt.transport.client.AsyncReqChannel.factory(self.opts)
try:
ret = yield channel.send(load, timeout=timeout)
raise tornado.gen.Return(ret)
finally:
channel.close()
def _fire_master(self, data=None, tag=None, events=None, pretag=None, timeout=60, sync=True, timeout_handler=None):
'''
Fire an event on the master, or drop message if unable to send.
'''
load = {'id': self.opts['id'],
'cmd': '_minion_event',
'pretag': pretag,
'tok': self.tok}
if events:
load['events'] = events
elif data and tag:
load['data'] = data
load['tag'] = tag
elif not data and tag:
load['data'] = {}
load['tag'] = tag
else:
return
if sync:
try:
self._send_req_sync(load, timeout)
except salt.exceptions.SaltReqTimeoutError:
log.info('fire_master failed: master could not be contacted. Request timed out.')
# very likely one of the masters is dead, status.master will flush it
self.functions['status.master'](self.opts['master'])
return False
except Exception:
log.info('fire_master failed: %s', traceback.format_exc())
return False
else:
if timeout_handler is None:
def handle_timeout(*_):
log.info('fire_master failed: master could not be contacted. Request timed out.')
# very likely one of the masters is dead, status.master will flush it
self.functions['status.master'](self.opts['master'])
return True
timeout_handler = handle_timeout
with tornado.stack_context.ExceptionStackContext(timeout_handler):
self._send_req_async(load, timeout, callback=lambda f: None) # pylint: disable=unexpected-keyword-arg
return True
@tornado.gen.coroutine
def _handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
# Ensure payload is unicode. Disregard failure to decode binary blobs.
if six.PY2:
data = salt.utils.data.decode(data, keep=True)
if 'user' in data:
log.info(
'User %s Executing command %s with jid %s',
data['user'], data['fun'], data['jid']
)
else:
log.info(
'Executing command %s with jid %s',
data['fun'], data['jid']
)
log.debug('Command details %s', data)
# Don't duplicate jobs
log.trace('Started JIDs: %s', self.jid_queue)
if self.jid_queue is not None:
if data['jid'] in self.jid_queue:
return
else:
self.jid_queue.append(data['jid'])
if len(self.jid_queue) > self.opts['minion_jid_queue_hwm']:
self.jid_queue.pop(0)
if isinstance(data['fun'], six.string_types):
if data['fun'] == 'sys.reload_modules':
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
self.schedule.functions = self.functions
self.schedule.returners = self.returners
process_count_max = self.opts.get('process_count_max')
process_count_max_sleep_secs = self.opts.get('process_count_max_sleep_secs')
if process_count_max > 0:
process_count = len(salt.utils.minion.running(self.opts))
while process_count >= process_count_max:
log.warning('Maximum number of processes (%s) reached while '
'executing jid %s, waiting %s seconds...',
process_count_max,
data['jid'],
process_count_max_sleep_secs)
yield tornado.gen.sleep(process_count_max_sleep_secs)
process_count = len(salt.utils.minion.running(self.opts))
# We stash an instance references to allow for the socket
# communication in Windows. You can't pickle functions, and thus
# python needs to be able to reconstruct the reference on the other
# side.
instance = self
multiprocessing_enabled = self.opts.get('multiprocessing', True)
if multiprocessing_enabled:
if sys.platform.startswith('win'):
# let python reconstruct the minion on the other side if we're
# running on windows
instance = None
with default_signals(signal.SIGINT, signal.SIGTERM):
process = SignalHandlingMultiprocessingProcess(
target=self._target, args=(instance, self.opts, data, self.connected)
)
else:
process = threading.Thread(
target=self._target,
args=(instance, self.opts, data, self.connected),
name=data['jid']
)
if multiprocessing_enabled:
with default_signals(signal.SIGINT, signal.SIGTERM):
# Reset current signals before starting the process in
# order not to inherit the current signal handlers
process.start()
else:
process.start()
# TODO: remove the windows specific check?
if multiprocessing_enabled and not salt.utils.platform.is_windows():
# we only want to join() immediately if we are daemonizing a process
process.join()
elif salt.utils.platform.is_windows():
self.win_proc.append(process)
def ctx(self):
'''
Return a single context manager for the minion's data
'''
if six.PY2:
return contextlib.nested(
self.functions.context_dict.clone(),
self.returners.context_dict.clone(),
self.executors.context_dict.clone(),
)
else:
exitstack = contextlib.ExitStack()
exitstack.enter_context(self.functions.context_dict.clone())
exitstack.enter_context(self.returners.context_dict.clone())
exitstack.enter_context(self.executors.context_dict.clone())
return exitstack
@classmethod
def _target(cls, minion_instance, opts, data, connected):
if not minion_instance:
minion_instance = cls(opts)
minion_instance.connected = connected
if not hasattr(minion_instance, 'functions'):
functions, returners, function_errors, executors = (
minion_instance._load_modules(grains=opts['grains'])
)
minion_instance.functions = functions
minion_instance.returners = returners
minion_instance.function_errors = function_errors
minion_instance.executors = executors
if not hasattr(minion_instance, 'serial'):
minion_instance.serial = salt.payload.Serial(opts)
if not hasattr(minion_instance, 'proc_dir'):
uid = salt.utils.user.get_uid(user=opts.get('user', None))
minion_instance.proc_dir = (
get_proc_dir(opts['cachedir'], uid=uid)
)
def run_func(minion_instance, opts, data):
if isinstance(data['fun'], tuple) or isinstance(data['fun'], list):
return Minion._thread_multi_return(minion_instance, opts, data)
else:
return Minion._thread_return(minion_instance, opts, data)
with tornado.stack_context.StackContext(functools.partial(RequestContext,
{'data': data, 'opts': opts})):
with tornado.stack_context.StackContext(minion_instance.ctx):
run_func(minion_instance, opts, data)
@classmethod
def _thread_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
fn_ = os.path.join(minion_instance.proc_dir, data['jid'])
if opts['multiprocessing'] and not salt.utils.platform.is_windows():
# Shutdown the multiprocessing before daemonizing
salt.log.setup.shutdown_multiprocessing_logging()
salt.utils.process.daemonize_if(opts)
# Reconfigure multiprocessing logging after daemonizing
salt.log.setup.setup_multiprocessing_logging()
salt.utils.process.appendproctitle('{0}._thread_return {1}'.format(cls.__name__, data['jid']))
sdata = {'pid': os.getpid()}
sdata.update(data)
log.info('Starting a new job %s with PID %s', data['jid'], sdata['pid'])
with salt.utils.files.fopen(fn_, 'w+b') as fp_:
fp_.write(minion_instance.serial.dumps(sdata))
ret = {'success': False}
function_name = data['fun']
executors = data.get('module_executors') or \
getattr(minion_instance, 'module_executors', []) or \
opts.get('module_executors', ['direct_call'])
allow_missing_funcs = any([
minion_instance.executors['{0}.allow_missing_func'.format(executor)](function_name)
for executor in executors
if '{0}.allow_missing_func' in minion_instance.executors
])
if function_name in minion_instance.functions or allow_missing_funcs is True:
try:
minion_blackout_violation = False
if minion_instance.connected and minion_instance.opts['pillar'].get('minion_blackout', False):
whitelist = minion_instance.opts['pillar'].get('minion_blackout_whitelist', [])
# this minion is blacked out. Only allow saltutil.refresh_pillar and the whitelist
if function_name != 'saltutil.refresh_pillar' and function_name not in whitelist:
minion_blackout_violation = True
# use minion_blackout_whitelist from grains if it exists
if minion_instance.opts['grains'].get('minion_blackout', False):
whitelist = minion_instance.opts['grains'].get('minion_blackout_whitelist', [])
if function_name != 'saltutil.refresh_pillar' and function_name not in whitelist:
minion_blackout_violation = True
if minion_blackout_violation:
raise SaltInvocationError('Minion in blackout mode. Set \'minion_blackout\' '
'to False in pillar or grains to resume operations. Only '
'saltutil.refresh_pillar allowed in blackout mode.')
if function_name in minion_instance.functions:
func = minion_instance.functions[function_name]
args, kwargs = load_args_and_kwargs(
func,
data['arg'],
data)
else:
# only run if function_name is not in minion_instance.functions and allow_missing_funcs is True
func = function_name
args, kwargs = data['arg'], data
minion_instance.functions.pack['__context__']['retcode'] = 0
if isinstance(executors, six.string_types):
executors = [executors]
elif not isinstance(executors, list) or not executors:
raise SaltInvocationError("Wrong executors specification: {0}. String or non-empty list expected".
format(executors))
if opts.get('sudo_user', '') and executors[-1] != 'sudo':
executors[-1] = 'sudo' # replace the last one with sudo
log.trace('Executors list %s', executors) # pylint: disable=no-member
for name in executors:
fname = '{0}.execute'.format(name)
if fname not in minion_instance.executors:
raise SaltInvocationError("Executor '{0}' is not available".format(name))
return_data = minion_instance.executors[fname](opts, data, func, args, kwargs)
if return_data is not None:
break
if isinstance(return_data, types.GeneratorType):
ind = 0
iret = {}
for single in return_data:
if isinstance(single, dict) and isinstance(iret, dict):
iret.update(single)
else:
if not iret:
iret = []
iret.append(single)
tag = tagify([data['jid'], 'prog', opts['id'], six.text_type(ind)], 'job')
event_data = {'return': single}
minion_instance._fire_master(event_data, tag)
ind += 1
ret['return'] = iret
else:
ret['return'] = return_data
retcode = minion_instance.functions.pack['__context__'].get(
'retcode',
salt.defaults.exitcodes.EX_OK
)
if retcode == salt.defaults.exitcodes.EX_OK:
# No nonzero retcode in __context__ dunder. Check if return
# is a dictionary with a "result" or "success" key.
try:
func_result = all(return_data.get(x, True)
for x in ('result', 'success'))
except Exception:
# return data is not a dict
func_result = True
if not func_result:
retcode = salt.defaults.exitcodes.EX_GENERIC
ret['retcode'] = retcode
ret['success'] = retcode == salt.defaults.exitcodes.EX_OK
except CommandNotFoundError as exc:
msg = 'Command required for \'{0}\' not found'.format(
function_name
)
log.debug(msg, exc_info=True)
ret['return'] = '{0}: {1}'.format(msg, exc)
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
except CommandExecutionError as exc:
log.error(
'A command in \'%s\' had a problem: %s',
function_name, exc,
exc_info_on_loglevel=logging.DEBUG
)
ret['return'] = 'ERROR: {0}'.format(exc)
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
except SaltInvocationError as exc:
log.error(
'Problem executing \'%s\': %s',
function_name, exc,
exc_info_on_loglevel=logging.DEBUG
)
ret['return'] = 'ERROR executing \'{0}\': {1}'.format(
function_name, exc
)
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
except TypeError as exc:
msg = 'Passed invalid arguments to {0}: {1}\n{2}'.format(
function_name, exc, func.__doc__ or ''
)
log.warning(msg, exc_info_on_loglevel=logging.DEBUG)
ret['return'] = msg
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
except Exception:
msg = 'The minion function caused an exception'
log.warning(msg, exc_info_on_loglevel=True)
salt.utils.error.fire_exception(salt.exceptions.MinionError(msg), opts, job=data)
ret['return'] = '{0}: {1}'.format(msg, traceback.format_exc())
ret['out'] = 'nested'
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
else:
docs = minion_instance.functions['sys.doc']('{0}*'.format(function_name))
if docs:
docs[function_name] = minion_instance.functions.missing_fun_string(function_name)
ret['return'] = docs
else:
ret['return'] = minion_instance.functions.missing_fun_string(function_name)
mod_name = function_name.split('.')[0]
if mod_name in minion_instance.function_errors:
ret['return'] += ' Possible reasons: \'{0}\''.format(
minion_instance.function_errors[mod_name]
)
ret['success'] = False
ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC
ret['out'] = 'nested'
ret['jid'] = data['jid']
ret['fun'] = data['fun']
ret['fun_args'] = data['arg']
if 'master_id' in data:
ret['master_id'] = data['master_id']
if 'metadata' in data:
if isinstance(data['metadata'], dict):
ret['metadata'] = data['metadata']
else:
log.warning('The metadata parameter must be a dictionary. Ignoring.')
if minion_instance.connected:
minion_instance._return_pub(
ret,
timeout=minion_instance._return_retry_timer()
)
# Add default returners from minion config
# Should have been coverted to comma-delimited string already
if isinstance(opts.get('return'), six.string_types):
if data['ret']:
data['ret'] = ','.join((data['ret'], opts['return']))
else:
data['ret'] = opts['return']
log.debug('minion return: %s', ret)
# TODO: make a list? Seems odd to split it this late :/
if data['ret'] and isinstance(data['ret'], six.string_types):
if 'ret_config' in data:
ret['ret_config'] = data['ret_config']
if 'ret_kwargs' in data:
ret['ret_kwargs'] = data['ret_kwargs']
ret['id'] = opts['id']
for returner in set(data['ret'].split(',')):
try:
returner_str = '{0}.returner'.format(returner)
if returner_str in minion_instance.returners:
minion_instance.returners[returner_str](ret)
else:
returner_err = minion_instance.returners.missing_fun_string(returner_str)
log.error(
'Returner %s could not be loaded: %s',
returner_str, returner_err
)
except Exception as exc:
log.exception(
'The return failed for job %s: %s', data['jid'], exc
)
@classmethod
def _thread_multi_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
fn_ = os.path.join(minion_instance.proc_dir, data['jid'])
if opts['multiprocessing'] and not salt.utils.platform.is_windows():
# Shutdown the multiprocessing before daemonizing
salt.log.setup.shutdown_multiprocessing_logging()
salt.utils.process.daemonize_if(opts)
# Reconfigure multiprocessing logging after daemonizing
salt.log.setup.setup_multiprocessing_logging()
salt.utils.process.appendproctitle('{0}._thread_multi_return {1}'.format(cls.__name__, data['jid']))
sdata = {'pid': os.getpid()}
sdata.update(data)
log.info('Starting a new job with PID %s', sdata['pid'])
with salt.utils.files.fopen(fn_, 'w+b') as fp_:
fp_.write(minion_instance.serial.dumps(sdata))
multifunc_ordered = opts.get('multifunc_ordered', False)
num_funcs = len(data['fun'])
if multifunc_ordered:
ret = {
'return': [None] * num_funcs,
'retcode': [None] * num_funcs,
'success': [False] * num_funcs
}
else:
ret = {
'return': {},
'retcode': {},
'success': {}
}
for ind in range(0, num_funcs):
if not multifunc_ordered:
ret['success'][data['fun'][ind]] = False
try:
minion_blackout_violation = False
if minion_instance.connected and minion_instance.opts['pillar'].get('minion_blackout', False):
whitelist = minion_instance.opts['pillar'].get('minion_blackout_whitelist', [])
# this minion is blacked out. Only allow saltutil.refresh_pillar and the whitelist
if data['fun'][ind] != 'saltutil.refresh_pillar' and data['fun'][ind] not in whitelist:
minion_blackout_violation = True
elif minion_instance.opts['grains'].get('minion_blackout', False):
whitelist = minion_instance.opts['grains'].get('minion_blackout_whitelist', [])
if data['fun'][ind] != 'saltutil.refresh_pillar' and data['fun'][ind] not in whitelist:
minion_blackout_violation = True
if minion_blackout_violation:
raise SaltInvocationError('Minion in blackout mode. Set \'minion_blackout\' '
'to False in pillar or grains to resume operations. Only '
'saltutil.refresh_pillar allowed in blackout mode.')
func = minion_instance.functions[data['fun'][ind]]
args, kwargs = load_args_and_kwargs(
func,
data['arg'][ind],
data)
minion_instance.functions.pack['__context__']['retcode'] = 0
key = ind if multifunc_ordered else data['fun'][ind]
ret['return'][key] = func(*args, **kwargs)
retcode = minion_instance.functions.pack['__context__'].get(
'retcode',
0
)
if retcode == 0:
# No nonzero retcode in __context__ dunder. Check if return
# is a dictionary with a "result" or "success" key.
try:
func_result = all(ret['return'][key].get(x, True)
for x in ('result', 'success'))
except Exception:
# return data is not a dict
func_result = True
if not func_result:
retcode = 1
ret['retcode'][key] = retcode
ret['success'][key] = retcode == 0
except Exception as exc:
trb = traceback.format_exc()
log.warning('The minion function caused an exception: %s', exc)
if multifunc_ordered:
ret['return'][ind] = trb
else:
ret['return'][data['fun'][ind]] = trb
ret['jid'] = data['jid']
ret['fun'] = data['fun']
ret['fun_args'] = data['arg']
if 'metadata' in data:
ret['metadata'] = data['metadata']
if minion_instance.connected:
minion_instance._return_pub(
ret,
timeout=minion_instance._return_retry_timer()
)
if data['ret']:
if 'ret_config' in data:
ret['ret_config'] = data['ret_config']
if 'ret_kwargs' in data:
ret['ret_kwargs'] = data['ret_kwargs']
for returner in set(data['ret'].split(',')):
ret['id'] = opts['id']
try:
minion_instance.returners['{0}.returner'.format(
returner
)](ret)
except Exception as exc:
log.error(
'The return failed for job %s: %s',
data['jid'], exc
)
def _return_pub(self, ret, ret_cmd='_return', timeout=60, sync=True):
'''
Return the data from the executed command to the master server
'''
jid = ret.get('jid', ret.get('__jid__'))
fun = ret.get('fun', ret.get('__fun__'))
if self.opts['multiprocessing']:
fn_ = os.path.join(self.proc_dir, jid)
if os.path.isfile(fn_):
try:
os.remove(fn_)
except (OSError, IOError):
# The file is gone already
pass
log.info('Returning information for job: %s', jid)
log.trace('Return data: %s', ret)
if ret_cmd == '_syndic_return':
load = {'cmd': ret_cmd,
'id': self.opts['uid'],
'jid': jid,
'fun': fun,
'arg': ret.get('arg'),
'tgt': ret.get('tgt'),
'tgt_type': ret.get('tgt_type'),
'load': ret.get('__load__')}
if '__master_id__' in ret:
load['master_id'] = ret['__master_id__']
load['return'] = {}
for key, value in six.iteritems(ret):
if key.startswith('__'):
continue
load['return'][key] = value
else:
load = {'cmd': ret_cmd,
'id': self.opts['id']}
for key, value in six.iteritems(ret):
load[key] = value
if 'out' in ret:
if isinstance(ret['out'], six.string_types):
load['out'] = ret['out']
else:
log.error(
'Invalid outputter %s. This is likely a bug.',
ret['out']
)
else:
try:
oput = self.functions[fun].__outputter__
except (KeyError, AttributeError, TypeError):
pass
else:
if isinstance(oput, six.string_types):
load['out'] = oput
if self.opts['cache_jobs']:
# Local job cache has been enabled
if ret['jid'] == 'req':
ret['jid'] = salt.utils.jid.gen_jid(self.opts)
salt.utils.minion.cache_jobs(self.opts, ret['jid'], ret)
if not self.opts['pub_ret']:
return ''
def timeout_handler(*_):
log.warning(
'The minion failed to return the job information for job %s. '
'This is often due to the master being shut down or '
'overloaded. If the master is running, consider increasing '
'the worker_threads value.', jid
)
return True
if sync:
try:
ret_val = self._send_req_sync(load, timeout=timeout)
except SaltReqTimeoutError:
timeout_handler()
return ''
else:
with tornado.stack_context.ExceptionStackContext(timeout_handler):
ret_val = self._send_req_async(load, timeout=timeout, callback=lambda f: None) # pylint: disable=unexpected-keyword-arg
log.trace('ret_val = %s', ret_val) # pylint: disable=no-member
return ret_val
def _return_pub_multi(self, rets, ret_cmd='_return', timeout=60, sync=True):
'''
Return the data from the executed command to the master server
'''
if not isinstance(rets, list):
rets = [rets]
jids = {}
for ret in rets:
jid = ret.get('jid', ret.get('__jid__'))
fun = ret.get('fun', ret.get('__fun__'))
if self.opts['multiprocessing']:
fn_ = os.path.join(self.proc_dir, jid)
if os.path.isfile(fn_):
try:
os.remove(fn_)
except (OSError, IOError):
# The file is gone already
pass
log.info('Returning information for job: %s', jid)
load = jids.setdefault(jid, {})
if ret_cmd == '_syndic_return':
if not load:
load.update({'id': self.opts['id'],
'jid': jid,
'fun': fun,
'arg': ret.get('arg'),
'tgt': ret.get('tgt'),
'tgt_type': ret.get('tgt_type'),
'load': ret.get('__load__'),
'return': {}})
if '__master_id__' in ret:
load['master_id'] = ret['__master_id__']
for key, value in six.iteritems(ret):
if key.startswith('__'):
continue
load['return'][key] = value
else:
load.update({'id': self.opts['id']})
for key, value in six.iteritems(ret):
load[key] = value
if 'out' in ret:
if isinstance(ret['out'], six.string_types):
load['out'] = ret['out']
else:
log.error(
'Invalid outputter %s. This is likely a bug.',
ret['out']
)
else:
try:
oput = self.functions[fun].__outputter__
except (KeyError, AttributeError, TypeError):
pass
else:
if isinstance(oput, six.string_types):
load['out'] = oput
if self.opts['cache_jobs']:
# Local job cache has been enabled
salt.utils.minion.cache_jobs(self.opts, load['jid'], ret)
load = {'cmd': ret_cmd,
'load': list(six.itervalues(jids))}
def timeout_handler(*_):
log.warning(
'The minion failed to return the job information for job %s. '
'This is often due to the master being shut down or '
'overloaded. If the master is running, consider increasing '
'the worker_threads value.', jid
)
return True
if sync:
try:
ret_val = self._send_req_sync(load, timeout=timeout)
except SaltReqTimeoutError:
timeout_handler()
return ''
else:
with tornado.stack_context.ExceptionStackContext(timeout_handler):
ret_val = self._send_req_async(load, timeout=timeout, callback=lambda f: None) # pylint: disable=unexpected-keyword-arg
log.trace('ret_val = %s', ret_val) # pylint: disable=no-member
return ret_val
def _state_run(self):
'''
Execute a state run based on information set in the minion config file
'''
if self.opts['startup_states']:
if self.opts.get('master_type', 'str') == 'disable' and \
self.opts.get('file_client', 'remote') == 'remote':
log.warning(
'Cannot run startup_states when \'master_type\' is set '
'to \'disable\' and \'file_client\' is set to '
'\'remote\'. Skipping.'
)
else:
data = {'jid': 'req', 'ret': self.opts.get('ext_job_cache', '')}
if self.opts['startup_states'] == 'sls':
data['fun'] = 'state.sls'
data['arg'] = [self.opts['sls_list']]
elif self.opts['startup_states'] == 'top':
data['fun'] = 'state.top'
data['arg'] = [self.opts['top_file']]
else:
data['fun'] = 'state.highstate'
data['arg'] = []
self._handle_decoded_payload(data)
def _refresh_grains_watcher(self, refresh_interval_in_minutes):
'''
Create a loop that will fire a pillar refresh to inform a master about a change in the grains of this minion
:param refresh_interval_in_minutes:
:return: None
'''
if '__update_grains' not in self.opts.get('schedule', {}):
if 'schedule' not in self.opts:
self.opts['schedule'] = {}
self.opts['schedule'].update({
'__update_grains':
{
'function': 'event.fire',
'args': [{}, 'grains_refresh'],
'minutes': refresh_interval_in_minutes
}
})
def _fire_master_minion_start(self):
# Send an event to the master that the minion is live
if self.opts['enable_legacy_startup_events']:
# Old style event. Defaults to False in Sodium release.
self._fire_master(
'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
'minion_start'
)
# send name spaced event
self._fire_master(
'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
tagify([self.opts['id'], 'start'], 'minion'),
)
def module_refresh(self, force_refresh=False, notify=False):
'''
Refresh the functions and returners.
'''
log.debug('Refreshing modules. Notify=%s', notify)
self.functions, self.returners, _, self.executors = self._load_modules(force_refresh, notify=notify)
self.schedule.functions = self.functions
self.schedule.returners = self.returners
def beacons_refresh(self):
'''
Refresh the functions and returners.
'''
log.debug('Refreshing beacons.')
self.beacons = salt.beacons.Beacon(self.opts, self.functions)
def matchers_refresh(self):
'''
Refresh the matchers
'''
log.debug('Refreshing matchers.')
self.matchers = salt.loader.matchers(self.opts)
# TODO: only allow one future in flight at a time?
@tornado.gen.coroutine
def pillar_refresh(self, force_refresh=False, notify=False):
'''
Refresh the pillar
'''
if self.connected:
log.debug('Refreshing pillar. Notify: %s', notify)
async_pillar = salt.pillar.get_async_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillarenv=self.opts.get('pillarenv'),
)
try:
self.opts['pillar'] = yield async_pillar.compile_pillar()
if notify:
evt = salt.utils.event.get_event('minion', opts=self.opts, listen=False)
evt.fire_event({'complete': True}, tag=salt.defaults.events.MINION_PILLAR_COMPLETE)
except SaltClientError:
# Do not exit if a pillar refresh fails.
log.error('Pillar data could not be refreshed. '
'One or more masters may be down!')
finally:
async_pillar.destroy()
self.module_refresh(force_refresh, notify)
self.matchers_refresh()
self.beacons_refresh()
def manage_schedule(self, tag, data):
'''
Refresh the functions and returners.
'''
func = data.get('func', None)
name = data.get('name', None)
schedule = data.get('schedule', None)
where = data.get('where', None)
persist = data.get('persist', None)
funcs = {'delete': ('delete_job', (name, persist)),
'add': ('add_job', (schedule, persist)),
'modify': ('modify_job',
(name, schedule, persist)),
'enable': ('enable_schedule', ()),
'disable': ('disable_schedule', ()),
'enable_job': ('enable_job', (name, persist)),
'disable_job': ('disable_job', (name, persist)),
'postpone_job': ('postpone_job', (name, data)),
'skip_job': ('skip_job', (name, data)),
'reload': ('reload', (schedule,)),
'list': ('list', (where,)),
'save_schedule': ('save_schedule', ()),
'get_next_fire_time': ('get_next_fire_time',
(name,))}
# Call the appropriate schedule function
try:
alias, params = funcs.get(func)
getattr(self.schedule, alias)(*params)
except TypeError:
log.error('Function "%s" is unavailable in salt.utils.scheduler',
func)
def manage_beacons(self, tag, data):
'''
Manage Beacons
'''
func = data.get('func', None)
name = data.get('name', None)
beacon_data = data.get('beacon_data', None)
include_pillar = data.get('include_pillar', None)
include_opts = data.get('include_opts', None)
funcs = {'add': ('add_beacon', (name, beacon_data)),
'modify': ('modify_beacon', (name, beacon_data)),
'delete': ('delete_beacon', (name,)),
'enable': ('enable_beacons', ()),
'disable': ('disable_beacons', ()),
'enable_beacon': ('enable_beacon', (name,)),
'disable_beacon': ('disable_beacon', (name,)),
'list': ('list_beacons', (include_opts,
include_pillar)),
'list_available': ('list_available_beacons', ()),
'validate_beacon': ('validate_beacon', (name,
beacon_data)),
'reset': ('reset', ())}
# Call the appropriate beacon function
try:
alias, params = funcs.get(func)
getattr(self.beacons, alias)(*params)
except AttributeError:
log.error('Function "%s" is unavailable in salt.beacons', func)
except TypeError as exc:
log.info(
'Failed to handle %s with data(%s). Error: %s',
tag, data, exc,
exc_info_on_loglevel=logging.DEBUG
)
def environ_setenv(self, tag, data):
'''
Set the salt-minion main process environment according to
the data contained in the minion event data
'''
environ = data.get('environ', None)
if environ is None:
return False
false_unsets = data.get('false_unsets', False)
clear_all = data.get('clear_all', False)
import salt.modules.environ as mod_environ
return mod_environ.setenv(environ, false_unsets, clear_all)
def _pre_tune(self):
'''
Set the minion running flag and issue the appropriate warnings if
the minion cannot be started or is already running
'''
if self._running is None:
self._running = True
elif self._running is False:
log.error(
'This %s was scheduled to stop. Not running %s.tune_in()',
self.__class__.__name__, self.__class__.__name__
)
return
elif self._running is True:
log.error(
'This %s is already running. Not running %s.tune_in()',
self.__class__.__name__, self.__class__.__name__
)
return
try:
log.info(
'%s is starting as user \'%s\'',
self.__class__.__name__, salt.utils.user.get_user()
)
except Exception as err:
# Only windows is allowed to fail here. See #3189. Log as debug in
# that case. Else, error.
log.log(
salt.utils.platform.is_windows() and logging.DEBUG or logging.ERROR,
'Failed to get the user who is starting %s',
self.__class__.__name__,
exc_info=err
)
def _mine_send(self, tag, data):
'''
Send mine data to the master
'''
channel = salt.transport.client.ReqChannel.factory(self.opts)
data['tok'] = self.tok
try:
ret = channel.send(data)
return ret
except SaltReqTimeoutError:
log.warning('Unable to send mine data to master.')
return None
finally:
channel.close()
def _handle_tag_module_refresh(self, tag, data):
'''
Handle a module_refresh event
'''
self.module_refresh(
force_refresh=data.get('force_refresh', False),
notify=data.get('notify', False)
)
@tornado.gen.coroutine
def _handle_tag_pillar_refresh(self, tag, data):
'''
Handle a pillar_refresh event
'''
yield self.pillar_refresh(
force_refresh=data.get('force_refresh', False),
notify=data.get('notify', False)
)
def _handle_tag_beacons_refresh(self, tag, data):
'''
Handle a beacon_refresh event
'''
self.beacons_refresh()
def _handle_tag_matchers_refresh(self, tag, data):
'''
Handle a matchers_refresh event
'''
self.matchers_refresh()
def _handle_tag_manage_schedule(self, tag, data):
'''
Handle a manage_schedule event
'''
self.manage_schedule(tag, data)
def _handle_tag_manage_beacons(self, tag, data):
'''
Handle a manage_beacons event
'''
self.manage_beacons(tag, data)
def _handle_tag_grains_refresh(self, tag, data):
'''
Handle a grains_refresh event
'''
if (data.get('force_refresh', False) or
self.grains_cache != self.opts['grains']):
self.pillar_refresh(force_refresh=True)
self.grains_cache = self.opts['grains']
def _handle_tag_environ_setenv(self, tag, data):
'''
Handle a environ_setenv event
'''
self.environ_setenv(tag, data)
def _handle_tag_minion_mine(self, tag, data):
'''
Handle a _minion_mine event
'''
self._mine_send(tag, data)
def _handle_tag_fire_master(self, tag, data):
'''
Handle a fire_master event
'''
if self.connected:
log.debug('Forwarding master event tag=%s', data['tag'])
self._fire_master(data['data'], data['tag'], data['events'], data['pretag'])
def _handle_tag_master_disconnected_failback(self, tag, data):
'''
Handle a master_disconnected_failback event
'''
# if the master disconnect event is for a different master, raise an exception
if tag.startswith(master_event(type='disconnected')) and data['master'] != self.opts['master']:
# not mine master, ignore
return
if tag.startswith(master_event(type='failback')):
# if the master failback event is not for the top master, raise an exception
if data['master'] != self.opts['master_list'][0]:
raise SaltException('Bad master \'{0}\' when mine failback is \'{1}\''.format(
data['master'], self.opts['master']))
# if the master failback event is for the current master, raise an exception
elif data['master'] == self.opts['master'][0]:
raise SaltException('Already connected to \'{0}\''.format(data['master']))
if self.connected:
# we are not connected anymore
self.connected = False
log.info('Connection to master %s lost', self.opts['master'])
# we can't use the config default here because the default '0' value is overloaded
# to mean 'if 0 disable the job', but when salt detects a timeout it also sets up
# these jobs
master_alive_interval = self.opts['master_alive_interval'] or 60
if self.opts['master_type'] != 'failover':
# modify the scheduled job to fire on reconnect
if self.opts['transport'] != 'tcp':
schedule = {
'function': 'status.master',
'seconds': master_alive_interval,
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master'],
'connected': False}
}
self.schedule.modify_job(name=master_event(type='alive', master=self.opts['master']),
schedule=schedule)
else:
# delete the scheduled job to don't interfere with the failover process
if self.opts['transport'] != 'tcp':
self.schedule.delete_job(name=master_event(type='alive', master=self.opts['master']),
persist=True)
log.info('Trying to tune in to next master from master-list')
if hasattr(self, 'pub_channel'):
self.pub_channel.on_recv(None)
if hasattr(self.pub_channel, 'auth'):
self.pub_channel.auth.invalidate()
if hasattr(self.pub_channel, 'close'):
self.pub_channel.close()
del self.pub_channel
# if eval_master finds a new master for us, self.connected
# will be True again on successful master authentication
try:
master, self.pub_channel = yield self.eval_master(
opts=self.opts,
failed=True,
failback=tag.startswith(master_event(type='failback')))
except SaltClientError:
pass
if self.connected:
self.opts['master'] = master
# re-init the subsystems to work with the new master
log.info(
'Re-initialising subsystems for new master %s',
self.opts['master']
)
# put the current schedule into the new loaders
self.opts['schedule'] = self.schedule.option('schedule')
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
# make the schedule to use the new 'functions' loader
self.schedule.functions = self.functions
self.pub_channel.on_recv(self._handle_payload)
self._fire_master_minion_start()
log.info('Minion is ready to receive requests!')
# update scheduled job to run with the new master addr
if self.opts['transport'] != 'tcp':
schedule = {
'function': 'status.master',
'seconds': master_alive_interval,
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master'],
'connected': True}
}
self.schedule.modify_job(name=master_event(type='alive', master=self.opts['master']),
schedule=schedule)
if self.opts['master_failback'] and 'master_list' in self.opts:
if self.opts['master'] != self.opts['master_list'][0]:
schedule = {
'function': 'status.ping_master',
'seconds': self.opts['master_failback_interval'],
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master_list'][0]}
}
self.schedule.modify_job(name=master_event(type='failback'),
schedule=schedule)
else:
self.schedule.delete_job(name=master_event(type='failback'), persist=True)
else:
self.restart = True
self.io_loop.stop()
def _handle_tag_master_connected(self, tag, data):
'''
Handle a master_connected event
'''
# handle this event only once. otherwise it will pollute the log
# also if master type is failover all the reconnection work is done
# by `disconnected` event handler and this event must never happen,
# anyway check it to be sure
if not self.connected and self.opts['master_type'] != 'failover':
log.info('Connection to master %s re-established', self.opts['master'])
self.connected = True
# modify the __master_alive job to only fire,
# if the connection is lost again
if self.opts['transport'] != 'tcp':
if self.opts['master_alive_interval'] > 0:
schedule = {
'function': 'status.master',
'seconds': self.opts['master_alive_interval'],
'jid_include': True,
'maxrunning': 1,
'return_job': False,
'kwargs': {'master': self.opts['master'],
'connected': True}
}
self.schedule.modify_job(name=master_event(type='alive', master=self.opts['master']),
schedule=schedule)
else:
self.schedule.delete_job(name=master_event(type='alive', master=self.opts['master']), persist=True)
def _handle_tag_schedule_return(self, tag, data):
'''
Handle a _schedule_return event
'''
# reporting current connection with master
if data['schedule'].startswith(master_event(type='alive', master='')):
if data['return']:
log.debug(
'Connected to master %s',
data['schedule'].split(master_event(type='alive', master=''))[1]
)
self._return_pub(data, ret_cmd='_return', sync=False)
def _handle_tag_salt_error(self, tag, data):
'''
Handle a _salt_error event
'''
if self.connected:
log.debug('Forwarding salt error event tag=%s', tag)
self._fire_master(data, tag)
def _handle_tag_salt_auth_creds(self, tag, data):
'''
Handle a salt_auth_creds event
'''
key = tuple(data['key'])
log.debug(
'Updating auth data for %s: %s -> %s',
key, salt.crypt.AsyncAuth.creds_map.get(key), data['creds']
)
salt.crypt.AsyncAuth.creds_map[tuple(data['key'])] = data['creds']
@tornado.gen.coroutine
def handle_event(self, package):
'''
Handle an event from the epull_sock (all local minion events)
'''
if not self.ready:
raise tornado.gen.Return()
tag, data = salt.utils.event.SaltEvent.unpack(package)
log.debug(
'Minion of \'%s\' is handling event tag \'%s\'',
self.opts['master'], tag
)
tag_functions = {
'beacons_refresh': self._handle_tag_beacons_refresh,
'environ_setenv': self._handle_tag_environ_setenv,
'fire_master': self._handle_tag_fire_master,
'grains_refresh': self._handle_tag_grains_refresh,
'matchers_refresh': self._handle_tag_matchers_refresh,
'manage_schedule': self._handle_tag_manage_schedule,
'manage_beacons': self._handle_tag_manage_beacons,
'_minion_mine': self._handle_tag_minion_mine,
'module_refresh': self._handle_tag_module_refresh,
'pillar_refresh': self._handle_tag_pillar_refresh,
'salt/auth/creds': self._handle_tag_salt_auth_creds,
'_salt_error': self._handle_tag_salt_error,
'__schedule_return': self._handle_tag_schedule_return,
master_event(type='disconnected'): self._handle_tag_master_disconnected_failback,
master_event(type='failback'): self._handle_tag_master_disconnected_failback,
master_event(type='connected'): self._handle_tag_master_connected,
}
# Run the appropriate function
for tag_function in tag_functions:
if tag.startswith(tag_function):
tag_functions[tag_function](tag, data)
def _fallback_cleanups(self):
'''
Fallback cleanup routines, attempting to fix leaked processes, threads, etc.
'''
# Add an extra fallback in case a forked process leaks through
multiprocessing.active_children()
# Cleanup Windows threads
if not salt.utils.platform.is_windows():
return
for thread in self.win_proc:
if not thread.is_alive():
thread.join()
try:
self.win_proc.remove(thread)
del thread
except (ValueError, NameError):
pass
def _setup_core(self):
'''
Set up the core minion attributes.
This is safe to call multiple times.
'''
if not self.ready:
# First call. Initialize.
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
self.serial = salt.payload.Serial(self.opts)
self.mod_opts = self._prep_mod_opts()
# self.matcher = Matcher(self.opts, self.functions)
self.matchers = salt.loader.matchers(self.opts)
self.beacons = salt.beacons.Beacon(self.opts, self.functions)
uid = salt.utils.user.get_uid(user=self.opts.get('user', None))
self.proc_dir = get_proc_dir(self.opts['cachedir'], uid=uid)
self.grains_cache = self.opts['grains']
self.ready = True
def setup_beacons(self, before_connect=False):
'''
Set up the beacons.
This is safe to call multiple times.
'''
self._setup_core()
loop_interval = self.opts['loop_interval']
new_periodic_callbacks = {}
if 'beacons' not in self.periodic_callbacks:
self.beacons = salt.beacons.Beacon(self.opts, self.functions)
def handle_beacons():
# Process Beacons
beacons = None
try:
beacons = self.process_beacons(self.functions)
except Exception:
log.critical('The beacon errored: ', exc_info=True)
if beacons and self.connected:
self._fire_master(events=beacons)
new_periodic_callbacks['beacons'] = tornado.ioloop.PeriodicCallback(
handle_beacons, loop_interval * 1000)
if before_connect:
# Make sure there is a chance for one iteration to occur before connect
handle_beacons()
if 'cleanup' not in self.periodic_callbacks:
new_periodic_callbacks['cleanup'] = tornado.ioloop.PeriodicCallback(
self._fallback_cleanups, loop_interval * 1000)
# start all the other callbacks
for periodic_cb in six.itervalues(new_periodic_callbacks):
periodic_cb.start()
self.periodic_callbacks.update(new_periodic_callbacks)
def setup_scheduler(self, before_connect=False):
'''
Set up the scheduler.
This is safe to call multiple times.
'''
self._setup_core()
loop_interval = self.opts['loop_interval']
new_periodic_callbacks = {}
if 'schedule' not in self.periodic_callbacks:
if 'schedule' not in self.opts:
self.opts['schedule'] = {}
if not hasattr(self, 'schedule'):
self.schedule = salt.utils.schedule.Schedule(
self.opts,
self.functions,
self.returners,
utils=self.utils,
cleanup=[master_event(type='alive')])
try:
if self.opts['grains_refresh_every']: # In minutes, not seconds!
log.debug(
'Enabling the grains refresher. Will run every %d minute(s).',
self.opts['grains_refresh_every']
)
self._refresh_grains_watcher(abs(self.opts['grains_refresh_every']))
except Exception as exc:
log.error(
'Exception occurred in attempt to initialize grain refresh '
'routine during minion tune-in: %s', exc
)
# TODO: actually listen to the return and change period
def handle_schedule():
self.process_schedule(self, loop_interval)
new_periodic_callbacks['schedule'] = tornado.ioloop.PeriodicCallback(handle_schedule, 1000)
if before_connect:
# Make sure there is a chance for one iteration to occur before connect
handle_schedule()
if 'cleanup' not in self.periodic_callbacks:
new_periodic_callbacks['cleanup'] = tornado.ioloop.PeriodicCallback(
self._fallback_cleanups, loop_interval * 1000)
# start all the other callbacks
for periodic_cb in six.itervalues(new_periodic_callbacks):
periodic_cb.start()
self.periodic_callbacks.update(new_periodic_callbacks)
# Main Minion Tune In
def tune_in(self, start=True):
'''
Lock onto the publisher. This is the main event loop for the minion
:rtype : None
'''
self._pre_tune()
log.debug('Minion \'%s\' trying to tune in', self.opts['id'])
if start:
if self.opts.get('beacons_before_connect', False):
self.setup_beacons(before_connect=True)
if self.opts.get('scheduler_before_connect', False):
self.setup_scheduler(before_connect=True)
self.sync_connect_master()
if self.connected:
self._fire_master_minion_start()
log.info('Minion is ready to receive requests!')
# Make sure to gracefully handle SIGUSR1
enable_sigusr1_handler()
# Make sure to gracefully handle CTRL_LOGOFF_EVENT
if HAS_WIN_FUNCTIONS:
salt.utils.win_functions.enable_ctrl_logoff_handler()
# On first startup execute a state run if configured to do so
self._state_run()
self.setup_beacons()
self.setup_scheduler()
# schedule the stuff that runs every interval
ping_interval = self.opts.get('ping_interval', 0) * 60
if ping_interval > 0 and self.connected:
def ping_master():
try:
def ping_timeout_handler(*_):
if self.opts.get('auth_safemode', False):
log.error('** Master Ping failed. Attempting to restart minion**')
delay = self.opts.get('random_reauth_delay', 5)
log.info('delaying random_reauth_delay %ss', delay)
try:
self.functions['service.restart'](service_name())
except KeyError:
# Probably no init system (running in docker?)
log.warning(
'ping_interval reached without response '
'from the master, but service.restart '
'could not be run to restart the minion '
'daemon. ping_interval requires that the '
'minion is running under an init system.'
)
self._fire_master('ping', 'minion_ping', sync=False, timeout_handler=ping_timeout_handler)
except Exception:
log.warning('Attempt to ping master failed.', exc_on_loglevel=logging.DEBUG)
self.periodic_callbacks['ping'] = tornado.ioloop.PeriodicCallback(ping_master, ping_interval * 1000)
self.periodic_callbacks['ping'].start()
# add handler to subscriber
if hasattr(self, 'pub_channel') and self.pub_channel is not None:
self.pub_channel.on_recv(self._handle_payload)
elif self.opts.get('master_type') != 'disable':
log.error('No connection to master found. Scheduled jobs will not run.')
if start:
try:
self.io_loop.start()
if self.restart:
self.destroy()
except (KeyboardInterrupt, RuntimeError): # A RuntimeError can be re-raised by Tornado on shutdown
self.destroy()
def _handle_payload(self, payload):
if payload is not None and payload['enc'] == 'aes':
if self._target_load(payload['load']):
self._handle_decoded_payload(payload['load'])
elif self.opts['zmq_filtering']:
# In the filtering enabled case, we'd like to know when minion sees something it shouldnt
log.trace(
'Broadcast message received not for this minion, Load: %s',
payload['load']
)
# If it's not AES, and thus has not been verified, we do nothing.
# In the future, we could add support for some clearfuncs, but
# the minion currently has no need.
def _target_load(self, load):
# Verify that the publication is valid
if 'tgt' not in load or 'jid' not in load or 'fun' not in load \
or 'arg' not in load:
return False
# Verify that the publication applies to this minion
# It's important to note that the master does some pre-processing
# to determine which minions to send a request to. So for example,
# a "salt -G 'grain_key:grain_val' test.ping" will invoke some
# pre-processing on the master and this minion should not see the
# publication if the master does not determine that it should.
if 'tgt_type' in load:
match_func = self.matchers.get('{0}_match.match'.format(load['tgt_type']), None)
if match_func is None:
return False
if load['tgt_type'] in ('grain', 'grain_pcre', 'pillar'):
delimiter = load.get('delimiter', DEFAULT_TARGET_DELIM)
if not match_func(load['tgt'], delimiter=delimiter):
return False
elif not match_func(load['tgt']):
return False
else:
if not self.matchers['glob_match.match'](load['tgt']):
return False
return True
def destroy(self):
'''
Tear down the minion
'''
if self._running is False:
return
self._running = False
if hasattr(self, 'schedule'):
del self.schedule
if hasattr(self, 'pub_channel') and self.pub_channel is not None:
self.pub_channel.on_recv(None)
if hasattr(self.pub_channel, 'close'):
self.pub_channel.close()
del self.pub_channel
if hasattr(self, 'periodic_callbacks'):
for cb in six.itervalues(self.periodic_callbacks):
cb.stop()
def __del__(self):
self.destroy()
class Syndic(Minion):
'''
Make a Syndic minion, this minion will use the minion keys on the
master to authenticate with a higher level master.
'''
def __init__(self, opts, **kwargs):
self._syndic_interface = opts.get('interface')
self._syndic = True
# force auth_safemode True because Syndic don't support autorestart
opts['auth_safemode'] = True
opts['loop_interval'] = 1
super(Syndic, self).__init__(opts, **kwargs)
self.mminion = salt.minion.MasterMinion(opts)
self.jid_forward_cache = set()
self.jids = {}
self.raw_events = []
self.pub_future = None
def _handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
# TODO: even do this??
data['to'] = int(data.get('to', self.opts['timeout'])) - 1
# Only forward the command if it didn't originate from ourselves
if data.get('master_id', 0) != self.opts.get('master_id', 1):
self.syndic_cmd(data)
def syndic_cmd(self, data):
'''
Take the now clear load and forward it on to the client cmd
'''
# Set up default tgt_type
if 'tgt_type' not in data:
data['tgt_type'] = 'glob'
kwargs = {}
# optionally add a few fields to the publish data
for field in ('master_id', # which master the job came from
'user', # which user ran the job
):
if field in data:
kwargs[field] = data[field]
def timeout_handler(*args):
log.warning('Unable to forward pub data: %s', args[1])
return True
with tornado.stack_context.ExceptionStackContext(timeout_handler):
self.local.pub_async(data['tgt'],
data['fun'],
data['arg'],
data['tgt_type'],
data['ret'],
data['jid'],
data['to'],
io_loop=self.io_loop,
callback=lambda _: None,
**kwargs)
def fire_master_syndic_start(self):
# Send an event to the master that the minion is live
if self.opts['enable_legacy_startup_events']:
# Old style event. Defaults to false in Sodium release.
self._fire_master(
'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
'syndic_start',
sync=False,
)
self._fire_master(
'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
tagify([self.opts['id'], 'start'], 'syndic'),
sync=False,
)
# TODO: clean up docs
def tune_in_no_block(self):
'''
Executes the tune_in sequence but omits extra logging and the
management of the event bus assuming that these are handled outside
the tune_in sequence
'''
# Instantiate the local client
self.local = salt.client.get_local_client(
self.opts['_minion_conf_file'], io_loop=self.io_loop)
# add handler to subscriber
self.pub_channel.on_recv(self._process_cmd_socket)
def _process_cmd_socket(self, payload):
if payload is not None and payload['enc'] == 'aes':
log.trace('Handling payload')
self._handle_decoded_payload(payload['load'])
# If it's not AES, and thus has not been verified, we do nothing.
# In the future, we could add support for some clearfuncs, but
# the syndic currently has no need.
@tornado.gen.coroutine
def reconnect(self):
if hasattr(self, 'pub_channel'):
self.pub_channel.on_recv(None)
if hasattr(self.pub_channel, 'close'):
self.pub_channel.close()
del self.pub_channel
# if eval_master finds a new master for us, self.connected
# will be True again on successful master authentication
master, self.pub_channel = yield self.eval_master(opts=self.opts)
if self.connected:
self.opts['master'] = master
self.pub_channel.on_recv(self._process_cmd_socket)
log.info('Minion is ready to receive requests!')
raise tornado.gen.Return(self)
def destroy(self):
'''
Tear down the syndic minion
'''
# We borrowed the local clients poller so give it back before
# it's destroyed. Reset the local poller reference.
super(Syndic, self).destroy()
if hasattr(self, 'local'):
del self.local
if hasattr(self, 'forward_events'):
self.forward_events.stop()
# TODO: need a way of knowing if the syndic connection is busted
class SyndicManager(MinionBase):
'''
Make a MultiMaster syndic minion, this minion will handle relaying jobs and returns from
all minions connected to it to the list of masters it is connected to.
Modes (controlled by `syndic_mode`:
sync: This mode will synchronize all events and publishes from higher level masters
cluster: This mode will only sync job publishes and returns
Note: jobs will be returned best-effort to the requesting master. This also means
(since we are using zmq) that if a job was fired and the master disconnects
between the publish and return, that the return will end up in a zmq buffer
in this Syndic headed to that original master.
In addition, since these classes all seem to use a mix of blocking and non-blocking
calls (with varying timeouts along the way) this daemon does not handle failure well,
it will (under most circumstances) stall the daemon for ~15s trying to forward events
to the down master
'''
# time to connect to upstream master
SYNDIC_CONNECT_TIMEOUT = 5
SYNDIC_EVENT_TIMEOUT = 5
def __init__(self, opts, io_loop=None):
opts['loop_interval'] = 1
super(SyndicManager, self).__init__(opts)
self.mminion = salt.minion.MasterMinion(opts)
# sync (old behavior), cluster (only returns and publishes)
self.syndic_mode = self.opts.get('syndic_mode', 'sync')
self.syndic_failover = self.opts.get('syndic_failover', 'random')
self.auth_wait = self.opts['acceptance_wait_time']
self.max_auth_wait = self.opts['acceptance_wait_time_max']
self._has_master = threading.Event()
self.jid_forward_cache = set()
if io_loop is None:
install_zmq()
self.io_loop = ZMQDefaultLoop.current()
else:
self.io_loop = io_loop
# List of events
self.raw_events = []
# Dict of rets: {master_id: {event_tag: job_ret, ...}, ...}
self.job_rets = {}
# List of delayed job_rets which was unable to send for some reason and will be resend to
# any available master
self.delayed = []
# Active pub futures: {master_id: (future, [job_ret, ...]), ...}
self.pub_futures = {}
def _spawn_syndics(self):
'''
Spawn all the coroutines which will sign in the syndics
'''
self._syndics = OrderedDict() # mapping of opts['master'] -> syndic
masters = self.opts['master']
if not isinstance(masters, list):
masters = [masters]
for master in masters:
s_opts = copy.copy(self.opts)
s_opts['master'] = master
self._syndics[master] = self._connect_syndic(s_opts)
@tornado.gen.coroutine
def _connect_syndic(self, opts):
'''
Create a syndic, and asynchronously connect it to a master
'''
auth_wait = opts['acceptance_wait_time']
failed = False
while True:
if failed:
if auth_wait < self.max_auth_wait:
auth_wait += self.auth_wait
log.debug(
"sleeping before reconnect attempt to %s [%d/%d]",
opts['master'],
auth_wait,
self.max_auth_wait,
)
yield tornado.gen.sleep(auth_wait) # TODO: log?
log.debug(
'Syndic attempting to connect to %s',
opts['master']
)
try:
syndic = Syndic(opts,
timeout=self.SYNDIC_CONNECT_TIMEOUT,
safe=False,
io_loop=self.io_loop,
)
yield syndic.connect_master(failed=failed)
# set up the syndic to handle publishes (specifically not event forwarding)
syndic.tune_in_no_block()
# Send an event to the master that the minion is live
syndic.fire_master_syndic_start()
log.info(
'Syndic successfully connected to %s',
opts['master']
)
break
except SaltClientError as exc:
failed = True
log.error(
'Error while bringing up syndic for multi-syndic. Is the '
'master at %s responding?', opts['master']
)
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
failed = True
log.critical(
'Unexpected error while connecting to %s',
opts['master'], exc_info=True
)
raise tornado.gen.Return(syndic)
def _mark_master_dead(self, master):
'''
Mark a master as dead. This will start the sign-in routine
'''
# if its connected, mark it dead
if self._syndics[master].done():
syndic = self._syndics[master].result() # pylint: disable=no-member
self._syndics[master] = syndic.reconnect()
else:
# TODO: debug?
log.info(
'Attempting to mark %s as dead, although it is already '
'marked dead', master
)
def _call_syndic(self, func, args=(), kwargs=None, master_id=None):
'''
Wrapper to call a given func on a syndic, best effort to get the one you asked for
'''
if kwargs is None:
kwargs = {}
successful = False
# Call for each master
for master, syndic_future in self.iter_master_options(master_id):
if not syndic_future.done() or syndic_future.exception():
log.error(
'Unable to call %s on %s, that syndic is not connected',
func, master
)
continue
try:
getattr(syndic_future.result(), func)(*args, **kwargs)
successful = True
except SaltClientError:
log.error(
'Unable to call %s on %s, trying another...',
func, master
)
self._mark_master_dead(master)
if not successful:
log.critical('Unable to call %s on any masters!', func)
def _return_pub_syndic(self, values, master_id=None):
'''
Wrapper to call the '_return_pub_multi' a syndic, best effort to get the one you asked for
'''
func = '_return_pub_multi'
for master, syndic_future in self.iter_master_options(master_id):
if not syndic_future.done() or syndic_future.exception():
log.error(
'Unable to call %s on %s, that syndic is not connected',
func, master
)
continue
future, data = self.pub_futures.get(master, (None, None))
if future is not None:
if not future.done():
if master == master_id:
# Targeted master previous send not done yet, call again later
return False
else:
# Fallback master is busy, try the next one
continue
elif future.exception():
# Previous execution on this master returned an error
log.error(
'Unable to call %s on %s, trying another...',
func, master
)
self._mark_master_dead(master)
del self.pub_futures[master]
# Add not sent data to the delayed list and try the next master
self.delayed.extend(data)
continue
future = getattr(syndic_future.result(), func)(values,
'_syndic_return',
timeout=self._return_retry_timer(),
sync=False)
self.pub_futures[master] = (future, values)
return True
# Loop done and didn't exit: wasn't sent, try again later
return False
def iter_master_options(self, master_id=None):
'''
Iterate (in order) over your options for master
'''
masters = list(self._syndics.keys())
if self.opts['syndic_failover'] == 'random':
shuffle(masters)
if master_id not in self._syndics:
master_id = masters.pop(0)
else:
masters.remove(master_id)
while True:
yield master_id, self._syndics[master_id]
if not masters:
break
master_id = masters.pop(0)
def _reset_event_aggregation(self):
self.job_rets = {}
self.raw_events = []
def reconnect_event_bus(self, something):
future = self.local.event.set_event_handler(self._process_event)
self.io_loop.add_future(future, self.reconnect_event_bus)
# Syndic Tune In
def tune_in(self):
'''
Lock onto the publisher. This is the main event loop for the syndic
'''
self._spawn_syndics()
# Instantiate the local client
self.local = salt.client.get_local_client(
self.opts['_minion_conf_file'], io_loop=self.io_loop)
self.local.event.subscribe('')
log.debug('SyndicManager \'%s\' trying to tune in', self.opts['id'])
# register the event sub to the poller
self.job_rets = {}
self.raw_events = []
self._reset_event_aggregation()
future = self.local.event.set_event_handler(self._process_event)
self.io_loop.add_future(future, self.reconnect_event_bus)
# forward events every syndic_event_forward_timeout
self.forward_events = tornado.ioloop.PeriodicCallback(self._forward_events,
self.opts['syndic_event_forward_timeout'] * 1000,
)
self.forward_events.start()
# Make sure to gracefully handle SIGUSR1
enable_sigusr1_handler()
self.io_loop.start()
def _process_event(self, raw):
# TODO: cleanup: Move down into event class
mtag, data = self.local.event.unpack(raw, self.local.event.serial)
log.trace('Got event %s', mtag) # pylint: disable=no-member
tag_parts = mtag.split('/')
if len(tag_parts) >= 4 and tag_parts[1] == 'job' and \
salt.utils.jid.is_jid(tag_parts[2]) and tag_parts[3] == 'ret' and \
'return' in data:
if 'jid' not in data:
# Not a job return
return
if self.syndic_mode == 'cluster' and data.get('master_id', 0) == self.opts.get('master_id', 1):
log.debug('Return received with matching master_id, not forwarding')
return
master = data.get('master_id')
jdict = self.job_rets.setdefault(master, {}).setdefault(mtag, {})
if not jdict:
jdict['__fun__'] = data.get('fun')
jdict['__jid__'] = data['jid']
jdict['__load__'] = {}
fstr = '{0}.get_load'.format(self.opts['master_job_cache'])
# Only need to forward each load once. Don't hit the disk
# for every minion return!
if data['jid'] not in self.jid_forward_cache:
jdict['__load__'].update(
self.mminion.returners[fstr](data['jid'])
)
self.jid_forward_cache.add(data['jid'])
if len(self.jid_forward_cache) > self.opts['syndic_jid_forward_cache_hwm']:
# Pop the oldest jid from the cache
tmp = sorted(list(self.jid_forward_cache))
tmp.pop(0)
self.jid_forward_cache = set(tmp)
if master is not None:
# __'s to make sure it doesn't print out on the master cli
jdict['__master_id__'] = master
ret = {}
for key in 'return', 'retcode', 'success':
if key in data:
ret[key] = data[key]
jdict[data['id']] = ret
else:
# TODO: config to forward these? If so we'll have to keep track of who
# has seen them
# if we are the top level masters-- don't forward all the minion events
if self.syndic_mode == 'sync':
# Add generic event aggregation here
if 'retcode' not in data:
self.raw_events.append({'data': data, 'tag': mtag})
def _forward_events(self):
log.trace('Forwarding events') # pylint: disable=no-member
if self.raw_events:
events = self.raw_events
self.raw_events = []
self._call_syndic('_fire_master',
kwargs={'events': events,
'pretag': tagify(self.opts['id'], base='syndic'),
'timeout': self._return_retry_timer(),
'sync': False,
},
)
if self.delayed:
res = self._return_pub_syndic(self.delayed)
if res:
self.delayed = []
for master in list(six.iterkeys(self.job_rets)):
values = list(six.itervalues(self.job_rets[master]))
res = self._return_pub_syndic(values, master_id=master)
if res:
del self.job_rets[master]
class ProxyMinionManager(MinionManager):
'''
Create the multi-minion interface but for proxy minions
'''
def _create_minion_object(self, opts, timeout, safe,
io_loop=None, loaded_base_name=None,
jid_queue=None):
'''
Helper function to return the correct type of object
'''
return ProxyMinion(opts,
timeout,
safe,
io_loop=io_loop,
loaded_base_name=loaded_base_name,
jid_queue=jid_queue)
def _metaproxy_call(opts, fn_name):
metaproxy = salt.loader.metaproxy(opts)
try:
metaproxy_name = opts['metaproxy']
except KeyError:
metaproxy_name = 'proxy'
log.trace(
'No metaproxy key found in opts for id %s. '
'Defaulting to standard proxy minion.',
opts['id']
)
metaproxy_fn = metaproxy_name + '.' + fn_name
return metaproxy[metaproxy_fn]
class ProxyMinion(Minion):
'''
This class instantiates a 'proxy' minion--a minion that does not manipulate
the host it runs on, but instead manipulates a device that cannot run a minion.
'''
# TODO: better name...
@tornado.gen.coroutine
def _post_master_init(self, master):
'''
Function to finish init after connecting to a master
This is primarily loading modules, pillars, etc. (since they need
to know which master they connected to)
If this function is changed, please check Minion._post_master_init
to see if those changes need to be propagated.
ProxyMinions need a significantly different post master setup,
which is why the differences are not factored out into separate helper
functions.
'''
mp_call = _metaproxy_call(self.opts, 'post_master_init')
return mp_call(self, master)
def _target_load(self, load):
'''
Verify that the publication is valid and applies to this minion
'''
mp_call = _metaproxy_call(self.opts, 'target_load')
return mp_call(self, load)
def _handle_payload(self, payload):
mp_call = _metaproxy_call(self.opts, 'handle_payload')
return mp_call(self, payload)
@tornado.gen.coroutine
def _handle_decoded_payload(self, data):
mp_call = _metaproxy_call(self.opts, 'handle_decoded_payload')
return mp_call(self, data)
@classmethod
def _target(cls, minion_instance, opts, data, connected):
mp_call = _metaproxy_call(opts, 'target')
return mp_call(cls, minion_instance, opts, data, connected)
@classmethod
def _thread_return(cls, minion_instance, opts, data):
mp_call = _metaproxy_call(opts, 'thread_return')
return mp_call(cls, minion_instance, opts, data)
@classmethod
def _thread_multi_return(cls, minion_instance, opts, data):
mp_call = _metaproxy_call(opts, 'thread_multi_return')
return mp_call(cls, minion_instance, opts, data)
class SProxyMinion(SMinion):
'''
Create an object that has loaded all of the minion module functions,
grains, modules, returners etc. The SProxyMinion allows developers to
generate all of the salt minion functions and present them with these
functions for general use.
'''
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
'''
self.opts['grains'] = salt.loader.grains(self.opts)
self.opts['pillar'] = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
saltenv=self.opts['saltenv'],
pillarenv=self.opts.get('pillarenv'),
).compile_pillar()
if 'proxy' not in self.opts['pillar'] and 'proxy' not in self.opts:
errmsg = (
'No "proxy" configuration key found in pillar or opts '
'dictionaries for id {id}. Check your pillar/options '
'configuration and contents. Salt-proxy aborted.'
).format(id=self.opts['id'])
log.error(errmsg)
self._running = False
raise SaltSystemExit(code=salt.defaults.exitcodes.EX_GENERIC, msg=errmsg)
if 'proxy' not in self.opts:
self.opts['proxy'] = self.opts['pillar']['proxy']
# Then load the proxy module
self.proxy = salt.loader.proxy(self.opts)
self.utils = salt.loader.utils(self.opts, proxy=self.proxy)
self.functions = salt.loader.minion_mods(self.opts, utils=self.utils, notify=False, proxy=self.proxy)
self.returners = salt.loader.returners(self.opts, self.functions, proxy=self.proxy)
self.matchers = salt.loader.matchers(self.opts)
self.functions['sys.reload_modules'] = self.gen_modules
self.executors = salt.loader.executors(self.opts, self.functions, proxy=self.proxy)
fq_proxyname = self.opts['proxy']['proxytype']
# we can then sync any proxymodules down from the master
# we do a sync_all here in case proxy code was installed by
# SPM or was manually placed in /srv/salt/_modules etc.
self.functions['saltutil.sync_all'](saltenv=self.opts['saltenv'])
self.functions.pack['__proxy__'] = self.proxy
self.proxy.pack['__salt__'] = self.functions
self.proxy.pack['__ret__'] = self.returners
self.proxy.pack['__pillar__'] = self.opts['pillar']
# Reload utils as well (chicken and egg, __utils__ needs __proxy__ and __proxy__ needs __utils__
self.utils = salt.loader.utils(self.opts, proxy=self.proxy)
self.proxy.pack['__utils__'] = self.utils
# Reload all modules so all dunder variables are injected
self.proxy.reload_modules()
if ('{0}.init'.format(fq_proxyname) not in self.proxy
or '{0}.shutdown'.format(fq_proxyname) not in self.proxy):
errmsg = 'Proxymodule {0} is missing an init() or a shutdown() or both. '.format(fq_proxyname) + \
'Check your proxymodule. Salt-proxy aborted.'
log.error(errmsg)
self._running = False
raise SaltSystemExit(code=salt.defaults.exitcodes.EX_GENERIC, msg=errmsg)
self.module_executors = self.proxy.get('{0}.module_executors'.format(fq_proxyname), lambda: [])()
proxy_init_fn = self.proxy[fq_proxyname + '.init']
proxy_init_fn(self.opts)
self.opts['grains'] = salt.loader.grains(self.opts, proxy=self.proxy)
# Sync the grains here so the proxy can communicate them to the master
self.functions['saltutil.sync_grains'](saltenv='base')
self.grains_cache = self.opts['grains']
self.ready = True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.