INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create a new bucket, or upload an object to a bucket. CLI Example to create a bucket: .. code-block:: bash salt myminion s3.put mybucket CLI Example to upload an object to a bucket: .. code-block:: bash salt myminion s3.put mybucket remotepath local_file=/path/to/file
def put(bucket, path=None, return_bin=False, action=None, local_file=None, key=None, keyid=None, service_url=None, verify_ssl=None, kms_keyid=None, location=None, role_arn=None, path_style=None, https_enable=None, headers=None, full_headers=False): ''' Create a new bucket, or upload an o...
Examine the keys, and populate as necessary
def _get_key(key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable): ''' Examine the keys, and populate as necessary ''' if not key and __salt__['config.option']('s3.key'): key = __salt__['config.option']('s3.key') if not keyid and __salt__['config.opt...
Generate a NT HASH CLI Example: .. code-block:: bash salt '*' pdbedit.generate_nt_hash my_passwd
def generate_nt_hash(password): ''' Generate a NT HASH CLI Example: .. code-block:: bash salt '*' pdbedit.generate_nt_hash my_passwd ''' return binascii.hexlify( hashlib.new( 'md4', password.encode('utf-16le') ).digest() ).upper()
List user accounts verbose : boolean return all information hashes : boolean include NT HASH and LM HASH in verbose output CLI Example: .. code-block:: bash salt '*' pdbedit.list
def list_users(verbose=True, hashes=False): ''' List user accounts verbose : boolean return all information hashes : boolean include NT HASH and LM HASH in verbose output CLI Example: .. code-block:: bash salt '*' pdbedit.list ''' users = {} if verbose else []...
Get user account details login : string login name hashes : boolean include NTHASH and LMHASH in verbose output CLI Example: .. code-block:: bash salt '*' pdbedit.get kaylee
def get_user(login, hashes=False): ''' Get user account details login : string login name hashes : boolean include NTHASH and LMHASH in verbose output CLI Example: .. code-block:: bash salt '*' pdbedit.get kaylee ''' users = list_users(verbose=True, hashes=has...
Delete user account login : string login name CLI Example: .. code-block:: bash salt '*' pdbedit.delete wash
def delete(login): ''' Delete user account login : string login name CLI Example: .. code-block:: bash salt '*' pdbedit.delete wash ''' if login in list_users(False): res = __salt__['cmd.run_all']( 'pdbedit --delete {login}'.format(login=_quote_args(lo...
Create user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text machine_account : boolean set to create a machine trust account instead CLI Example: .. code-block:: bash ...
def create(login, password, password_hashed=False, machine_account=False): ''' Create user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text machine_account : boolean set to c...
Modify user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text domain : string users domain profile : string profile path script : string logon script drive...
def modify( login, password=None, password_hashed=False, domain=None, profile=None, script=None, drive=None, homedir=None, fullname=None, account_desc=None, account_control=None, machine_sid=None, user_sid=None, reset_login_hours=False, reset_bad_password_count=False, ): ''' Modify user ...
Check time range
def _validate_time_range(trange, status, msg): ''' Check time range ''' # If trange is empty, just return the current status & msg if not trange: return status, msg if not isinstance(trange, dict): status = False msg = ('The time_range parameter for ' 'wtm...
Validate the beacon configuration
def validate(config): ''' Validate the beacon configuration ''' vstatus = True vmsg = 'Valid beacon configuration' # Configuration for wtmp beacon should be a list of dicts if not isinstance(config, list): vstatus = False vmsg = ('Configuration for wtmp beacon must be a list...
Ensure the named service is running. name Service name as defined in the supervisor configuration file restart Whether to force a restart update Whether to update the supervisor configuration. user Name of the user to run the supervisorctl command .. versiona...
def running(name, restart=False, update=False, user=None, conf_file=None, bin_env=None, **kwargs): ''' Ensure the named service is running. name Service name as defined in the supervisor configuration file restart ...
Ensure the named service is dead (not running). name Service name as defined in the supervisor configuration file user Name of the user to run the supervisorctl command .. versionadded:: 0.17.0 conf_file path to supervisorctl config file bin_env path to super...
def dead(name, user=None, conf_file=None, bin_env=None, **kwargs): ''' Ensure the named service is dead (not running). name Service name as defined in the supervisor configuration file user Name of the user to run the supervisorctl command ....
The supervisord watcher, called to invoke the watch command. Always restart on watch .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being t...
def mod_watch(name, restart=True, update=False, user=None, conf_file=None, bin_env=None, **kwargs): ''' The supervisord watcher, called to invoke the watch command. Always restart on watch .. note:: This state e...
Render a Cheetah template. :rtype: A Python data structure
def render(cheetah_data, saltenv='base', sls='', method='xml', **kws): ''' Render a Cheetah template. :rtype: A Python data structure ''' if not HAS_LIBS: return {} if not isinstance(cheetah_data, six.string_types): cheetah_data = cheetah_data.read() if cheetah_data.starts...
Get configuration items for URL, Username and Password
def _config(): ''' Get configuration items for URL, Username and Password ''' status_url = __salt__['config.get']('nagios.status_url') or \ __salt__['config.get']('nagios:status_url') if not status_url: raise CommandExecutionError('Missing Nagios URL in the configuration.') user...
Send query along to Nagios.
def _status_query(query, hostname, enumerate=None, service=None): ''' Send query along to Nagios. ''' config = _config() data = None params = { 'hostname': hostname, 'query': query, } ret = { 'result': False } if enumerate: params['formatoptions...
Check status of a particular host By default statuses are returned in a numeric format. Parameters: hostname The hostname to check the status of the service in Nagios. numeric Turn to false in order to return status in text format ('OK' instead of 0, 'Warning' instead of 1 etc...
def host_status(hostname=None, **kwargs): ''' Check status of a particular host By default statuses are returned in a numeric format. Parameters: hostname The hostname to check the status of the service in Nagios. numeric Turn to false in order to return status in text format ...
Check status of a particular service on a host on it in Nagios. By default statuses are returned in a numeric format. Parameters: hostname The hostname to check the status of the service in Nagios. service The service to check the status of in Nagios. numeric Turn to fals...
def service_status(hostname=None, service=None, **kwargs): ''' Check status of a particular service on a host on it in Nagios. By default statuses are returned in a numeric format. Parameters: hostname The hostname to check the status of the service in Nagios. service The serv...
Set a key/value pair in a keyring service
def set_(key, value, service=None, profile=None): ''' Set a key/value pair in a keyring service ''' service = _get_service(service, profile) keyring.set_password(service, key, value)
Get a value from a keyring service
def get(key, service=None, profile=None): ''' Get a value from a keyring service ''' service = _get_service(service, profile) return keyring.get_password(service, key)
Log outcome to sentry. The returner tries to identify errors and report them as such. All other messages will be reported at info level. Failed states will be appended as separate list for convenience.
def returner(ret): ''' Log outcome to sentry. The returner tries to identify errors and report them as such. All other messages will be reported at info level. Failed states will be appended as separate list for convenience. ''' try: _connect_sentry(_get_message(ret), ret) except Ex...
Connect to the Sentry server
def _connect_sentry(message, result): ''' Connect to the Sentry server ''' pillar_data = __salt__['pillar.raw']() grains = __salt__['grains.items']() raven_config = pillar_data['raven'] hide_pillar = raven_config.get('hide_pillar') sentry_data = { 'result': result, 'pilla...
Return a list of registered VMs, with minimal information CLI Example: .. code-block:: bash salt '*' vboxmanage.list_nodes_min
def list_nodes_min(): ''' Return a list of registered VMs, with minimal information CLI Example: .. code-block:: bash salt '*' vboxmanage.list_nodes_min ''' ret = {} cmd = '{0} list vms'.format(vboxcmd()) for line in salt.modules.cmdmod.run(cmd).splitlines(): if not li...
Return a list of registered VMs CLI Example: .. code-block:: bash salt '*' vboxmanage.list_nodes
def list_nodes(): ''' Return a list of registered VMs CLI Example: .. code-block:: bash salt '*' vboxmanage.list_nodes ''' ret = {} nodes = list_nodes_full() for node in nodes: ret[node] = { 'id': nodes[node]['UUID'], 'image': nodes[node]['Guest...
Start a VM CLI Example: .. code-block:: bash salt '*' vboxmanage.start my_vm
def start(name): ''' Start a VM CLI Example: .. code-block:: bash salt '*' vboxmanage.start my_vm ''' ret = {} cmd = '{0} startvm {1}'.format(vboxcmd(), name) ret = salt.modules.cmdmod.run(cmd).splitlines() return ret
Register a VM CLI Example: .. code-block:: bash salt '*' vboxmanage.register my_vm_filename
def register(filename): ''' Register a VM CLI Example: .. code-block:: bash salt '*' vboxmanage.register my_vm_filename ''' if not os.path.isfile(filename): raise CommandExecutionError( 'The specified filename ({0}) does not exist.'.format(filename) ) ...
Unregister a VM CLI Example: .. code-block:: bash salt '*' vboxmanage.unregister my_vm_filename
def unregister(name, delete=False): ''' Unregister a VM CLI Example: .. code-block:: bash salt '*' vboxmanage.unregister my_vm_filename ''' nodes = list_nodes_min() if name not in nodes: raise CommandExecutionError( 'The specified VM ({0}) is not registered.'.f...
Create a new VM CLI Example: .. code-block:: bash salt 'hypervisor' vboxmanage.create <name>
def create(name, groups=None, ostype=None, register=True, basefolder=None, new_uuid=None, **kwargs): ''' Create a new VM CLI Example: .. code-block:: bash salt 'hypervisor' vboxmanage.create <name> ''' nodes = list_node...
Clone a new VM from an existing VM CLI Example: .. code-block:: bash salt 'hypervisor' vboxmanage.clonevm <name> <new_name>
def clonevm(name=None, uuid=None, new_name=None, snapshot_uuid=None, snapshot_name=None, mode='machine', options=None, basefolder=None, new_uuid=None, register=False, groups=None, **kwargs...
Clone a new VM from an existing VM CLI Example: .. code-block:: bash salt 'hypervisor' vboxmanage.clonemedium <name> <new_name>
def clonemedium(medium, uuid_in=None, file_in=None, uuid_out=None, file_out=None, mformat=None, variant=None, existing=False, **kwargs): ''' Clone a new VM from an existing VM CLI...
Return a list of a specific type of item. The following items are available: vms runningvms ostypes hostdvds hostfloppies intnets bridgedifs hostonlyifs natnets dhcpservers hostinfo hostcpuids hddbackends hd...
def list_items(item, details=False, group_by='UUID'): ''' Return a list of a specific type of item. The following items are available: vms runningvms ostypes hostdvds hostfloppies intnets bridgedifs hostonlyifs natnets dhcpservers ...
Return strings values as python unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html
def _unicode_output(cursor, name, default_type, size, precision, scale): ''' Return strings values as python unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html ''' if default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracl...
uri = user/password@host[:port]/sid[servicename as {sysdba|sysoper}] or uri = sid[ as {sysdba|sysoper}] (this syntax only makes sense on non-Windows minions, ORAHOME is taken from oratab) Return cx_Oracle.Connection instance
def _connect(uri): ''' uri = user/password@host[:port]/sid[servicename as {sysdba|sysoper}] or uri = sid[ as {sysdba|sysoper}] (this syntax only makes sense on non-Windows minions, ORAHOME is taken from oratab) Return cx_Oracle.Connection instance ''' # cx_Oracle.Connection() does not...
Return ORACLE_HOME for a given SID found in oratab Note: only works with Unix-like minions
def _parse_oratab(sid): ''' Return ORACLE_HOME for a given SID found in oratab Note: only works with Unix-like minions ''' if __grains__.get('kernel') in ('Linux', 'AIX', 'FreeBSD', 'OpenBSD', 'NetBSD'): ORATAB = '/etc/oratab' elif __grains__.get('kernel') in 'SunOS': ORATAB = '...
Run SQL query and return result CLI Example: .. code-block:: bash salt '*' oracle.run_query my_db "select * from my_table"
def run_query(db, query): ''' Run SQL query and return result CLI Example: .. code-block:: bash salt '*' oracle.run_query my_db "select * from my_table" ''' if db in [x.keys()[0] for x in show_dbs()]: conn = _connect(show_dbs(db)[db]['uri']) else: log.debug('No uri...
Show databases configuration from pillar. Filter by `*args` CLI Example: .. code-block:: bash salt '*' oracle.show_dbs salt '*' oracle.show_dbs my_db
def show_dbs(*dbs): ''' Show databases configuration from pillar. Filter by `*args` CLI Example: .. code-block:: bash salt '*' oracle.show_dbs salt '*' oracle.show_dbs my_db ''' if dbs: log.debug('get db versions for: %s', dbs) result = {} for db in dbs...
Server Version (select banner from v$version) CLI Example: .. code-block:: bash salt '*' oracle.version salt '*' oracle.version my_db
def version(*dbs): ''' Server Version (select banner from v$version) CLI Example: .. code-block:: bash salt '*' oracle.version salt '*' oracle.version my_db ''' pillar_dbs = __salt__['pillar.get']('oracle:dbs') get_version = lambda x: [ r[0] for r in run_query(x, ...
Show Environment used by Oracle Client CLI Example: .. code-block:: bash salt '*' oracle.show_env .. note:: at first _connect() ``NLS_LANG`` will forced to '.AL32UTF8'
def show_env(): ''' Show Environment used by Oracle Client CLI Example: .. code-block:: bash salt '*' oracle.show_env .. note:: at first _connect() ``NLS_LANG`` will forced to '.AL32UTF8' ''' envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG'] result = {} for ...
Retrieve GECOS field info and return it in dictionary form
def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4...
Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with usermod.
def _build_gecos(gecos_dict): ''' Accepts a dictionary entry containing GECOS field names and their values, and returns a full GECOS comment string, to be used with usermod. ''' return '{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''), gecos_dict.get('roomnu...
Common code to change a user's GECOS information
def _update_gecos(name, key, value): ''' Common code to change a user's GECOS information ''' if not isinstance(value, six.string_types): value = six.text_type(value) pre_info = _get_gecos(name) if not pre_info: return False if value == pre_info[key]: return True ...
Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell>
def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, **kwargs): ''' Add a user to the minion CLI Example: ...
Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True
def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.data.is_true(force): log.warning( 'userdel does not support force-deleting user while...
Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376
def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if gid...
Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh
def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) ...
Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the files from the skeleton directory. CLI E...
def chhome(name, home, persist=False): ''' Set a new home directory for an existing user name Username to modify home New home directory to set persist : False Set to ``True`` to prevent configuration files in the new home directory from being overwritten by the fi...
Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Other...
def chgroups(name, groups, append=False): ''' Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these group...
Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name
def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info...
Creates a 'singleton' manager to communicate with a local virtualbox hypervisor. @return: @rtype: VirtualBoxManager
def vb_get_manager(): ''' Creates a 'singleton' manager to communicate with a local virtualbox hypervisor. @return: @rtype: VirtualBoxManager ''' global _virtualboxManager if _virtualboxManager is None and HAS_LIBS: salt.utils.compat.reload(vboxapi) _virtualboxManager = vboxa...
Needed for certain operations in the SDK e.g creating sessions @return: @rtype: IVirtualBox
def vb_get_box(): ''' Needed for certain operations in the SDK e.g creating sessions @return: @rtype: IVirtualBox ''' vb_get_manager() try: # This works in older versions of the SDK, but does not seem to work anymore. vbox = _virtualboxManager.vbox except AttributeError:...
Max number of slots any machine can have @return: @rtype: number
def vb_get_max_network_slots(): ''' Max number of slots any machine can have @return: @rtype: number ''' sysprops = vb_get_box().systemProperties totals = [ sysprops.getMaxNetworkAdapters(adapter_type) for adapter_type in [ 1, # PIIX3 A PIIX3 (PCI IDE ISA Xcelera...
A valid machine_name or a machine is needed to make this work! @param machine_name: @type machine_name: str @param machine: @type machine: IMachine @return: INetorkAdapter's converted to dicts @rtype: [dict]
def vb_get_network_adapters(machine_name=None, machine=None): ''' A valid machine_name or a machine is needed to make this work! @param machine_name: @type machine_name: str @param machine: @type machine: IMachine @return: INetorkAdapter's converted to dicts @rtype: [dict] ''' ...
Wait until a machine has a network address to return or quit after the timeout @param timeout: in seconds @type timeout: float @param step: How regularly we want to check for ips (in seconds) @type step: float @param machine_name: @type machine_name: str @param machine: @type machine: I...
def vb_wait_for_network_address(timeout, step=None, machine_name=None, machine=None, wait_for_pattern=None): ''' Wait until a machine has a network address to return or quit after the timeout @param timeout: in seconds @type timeout: float @param step: How regularly we want to check for ips (in sec...
Waits until a session state has been reached, checking at regular intervals. @param xp_session: @type xp_session: ISession from the Virtualbox API @param state: The constant descriptor according to the docs @type state: str @param timeout: in seconds @type timeout: int | float @param step: ...
def vb_wait_for_session_state(xp_session, state='Unlocked', timeout=10, step=None): ''' Waits until a session state has been reached, checking at regular intervals. @param xp_session: @type xp_session: ISession from the Virtualbox API @param state: The constant descriptor according to the docs ...
TODO distinguish between private and public addresses A valid machine_name or a machine is needed to make this work! !!! Guest prerequisite: GuestAddition !!! Thanks to Shrikant Havale for the StackOverflow answer http://stackoverflow.com/a/29335390 More information on guest properties: http...
def vb_get_network_addresses(machine_name=None, machine=None, wait_for_pattern=None): ''' TODO distinguish between private and public addresses A valid machine_name or a machine is needed to make this work! !!! Guest prerequisite: GuestAddition !!! Thanks to Shrikant Havale for the StackO...
Which machines does the hypervisor have @param kwargs: Passed to vb_xpcom_to_attribute_dict to filter the attributes @type kwargs: dict @return: Untreated dicts of the machines known to the hypervisor @rtype: [{}]
def vb_list_machines(**kwargs): ''' Which machines does the hypervisor have @param kwargs: Passed to vb_xpcom_to_attribute_dict to filter the attributes @type kwargs: dict @return: Untreated dicts of the machines known to the hypervisor @rtype: [{}] ''' manager = vb_get_manager() mac...
Creates a machine on the virtualbox hypervisor TODO pass more params to customize machine creation @param name: @type name: str @return: Representation of the created machine @rtype: dict
def vb_create_machine(name=None): ''' Creates a machine on the virtualbox hypervisor TODO pass more params to customize machine creation @param name: @type name: str @return: Representation of the created machine @rtype: dict ''' vbox = vb_get_box() log.info('Create virtualbox m...
Tells virtualbox to create a VM by cloning from an existing one @param name: Name for the new VM @type name: str @param clone_from: @type clone_from: str @param timeout: maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return dict of resulting VM
def vb_clone_vm( name=None, clone_from=None, clone_mode=0, timeout=10000, **kwargs ): ''' Tells virtualbox to create a VM by cloning from an existing one @param name: Name for the new VM @type name: str @param clone_from: @type clone_from: str @param timeout: maximum tim...
Helper to try and start machines @param machine: @type machine: IMachine @param session: @type session: ISession @return: @rtype: IProgress or None
def _start_machine(machine, session): ''' Helper to try and start machines @param machine: @type machine: IMachine @param session: @type session: ISession @return: @rtype: IProgress or None ''' try: return machine.launchVMProcess(session, '', '') except Exception as ...
Tells Virtualbox to start up a VM. Blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of started VM
def vb_start_vm(name=None, timeout=10000, **kwargs): ''' Tells Virtualbox to start up a VM. Blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of started VM ''' ...
Tells Virtualbox to stop a VM. This is a blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of stopped VM
def vb_stop_vm(name=None, timeout=10000, **kwargs): ''' Tells Virtualbox to stop a VM. This is a blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of stopped VM ''...
Attempts to get rid of a machine and all its files from the hypervisor @param name: @type name: str @param timeout int timeout in milliseconds
def vb_destroy_machine(name=None, timeout=10000): ''' Attempts to get rid of a machine and all its files from the hypervisor @param name: @type name: str @param timeout int timeout in milliseconds ''' vbox = vb_get_box() log.info('Destroying machine %s', name) machine = vbox.findMach...
Attempts to build a dict from an XPCOM object. Attributes that don't exist in the object return an empty string. attribute_list = list of str or tuple(str,<a class>) e.g attributes=[('bad_attribute', list)] --> { 'bad_attribute': [] } @param xpcom: @type xpcom: @param interface_name: Which in...
def vb_xpcom_to_attribute_dict(xpcom, interface_name=None, attributes=None, excluded_attributes=None, extra_attributes=None ): ''' Attempts to build a dict f...
Make machine presentable for outside world. !!!Modifies the input machine!!! @param machine: @type machine: dict @return: the modified input machine @rtype: dict
def treat_machine_dict(machine): ''' Make machine presentable for outside world. !!!Modifies the input machine!!! @param machine: @type machine: dict @return: the modified input machine @rtype: dict ''' machine.update({ 'id': machine.get('id', ''), 'image': machine....
Checks in with the hypervisor to see if the machine with the given name is known @param name: @type name: @return: @rtype:
def vb_machine_exists(name): ''' Checks in with the hypervisor to see if the machine with the given name is known @param name: @type name: @return: @rtype: ''' try: vbox = vb_get_box() vbox.findMachine(name) return True except Exception as e: if isinst...
Attempts to fetch a machine from Virtualbox and convert it to a dict @param name: The unique name of the machine @type name: @param kwargs: To be passed to vb_xpcom_to_attribute_dict @type kwargs: @return: @rtype: dict
def vb_get_machine(name, **kwargs): ''' Attempts to fetch a machine from Virtualbox and convert it to a dict @param name: The unique name of the machine @type name: @param kwargs: To be passed to vb_xpcom_to_attribute_dict @type kwargs: @return: @rtype: dict ''' vbox = vb_get_bo...
Compare before and after results from various salt functions, returning a dict describing the changes that were made.
def compare_dicts(old=None, new=None): ''' Compare before and after results from various salt functions, returning a dict describing the changes that were made. ''' ret = {} for key in set((new or {})).union((old or {})): if key not in old: # New key ret[key] = {'...
Compare before and after results from various salt functions, returning a dict describing the changes that were made
def compare_lists(old=None, new=None): ''' Compare before and after results from various salt functions, returning a dict describing the changes that were made ''' ret = dict() for item in new: if item not in old: ret['new'] = item for item in old: if item not in ...
Generic function which will decode whichever type is passed, if necessary. Optionally use to_str=True to ensure strings are str types and not unicode on Python 2. If `strict` is True, and `keep` is False, and we fail to decode, a UnicodeDecodeError will be raised. Passing `keep` as True allows for the ...
def decode(data, encoding=None, errors='strict', keep=False, normalize=False, preserve_dict_class=False, preserve_tuples=False, to_str=False): ''' Generic function which will decode whichever type is passed, if necessary. Optionally use to_str=True to ensure strings are str types and n...
Decode all string values to Unicode. Optionally use to_str=True to ensure strings are str types and not unicode on Python 2.
def decode_dict(data, encoding=None, errors='strict', keep=False, normalize=False, preserve_dict_class=False, preserve_tuples=False, to_str=False): ''' Decode all string values to Unicode. Optionally use to_str=True to ensure strings are str types and not unicode on Python 2....
Decode all string values to Unicode. Optionally use to_str=True to ensure strings are str types and not unicode on Python 2.
def decode_tuple(data, encoding=None, errors='strict', keep=False, normalize=False, preserve_dict_class=False, to_str=False): ''' Decode all string values to Unicode. Optionally use to_str=True to ensure strings are str types and not unicode on Python 2. ''' return tuple( de...
Generic function which will encode whichever type is passed, if necessary If `strict` is True, and `keep` is False, and we fail to encode, a UnicodeEncodeError will be raised. Passing `keep` as True allows for the original value to silently be returned in cases where encoding fails. This can be useful ...
def encode(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False, preserve_tuples=False): ''' Generic function which will encode whichever type is passed, if necessary If `strict` is True, and `keep` is False, and we fail to encode, a UnicodeEncodeError will be raised. ...
Encode all string values to bytes
def encode_dict(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False, preserve_tuples=False): ''' Encode all string values to bytes ''' rv = data.__class__() if preserve_dict_class else {} for key, value in six.iteritems(data): if isinstance(key, tuple)...
Encode all string values to bytes
def encode_list(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False, preserve_tuples=False): ''' Encode all string values to bytes ''' rv = [] for item in data: if isinstance(item, list): item = encode_list(item, encoding, errors, keep, ...
Encode all string values to Unicode
def encode_tuple(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False): ''' Encode all string values to Unicode ''' return tuple( encode_list(data, encoding, errors, keep, preserve_dict_class, True))
Common code to filter data structures like grains and pillar
def filter_by(lookup_dict, lookup, traverse, merge=None, default='default', base=None): ''' Common code to filter data structures like grains and pillar ''' ret = None # Default value would be an empty list if lookup not found ...
Traverse a dict using a colon-delimited (or otherwise delimited, using the 'delimiter' param) target string. The target 'foo:bar:baz' will return data['foo']['bar']['baz'] if this value exists, and will otherwise return the dict in the default argument.
def traverse_dict(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM): ''' Traverse a dict using a colon-delimited (or otherwise delimited, using the 'delimiter' param) target string. The target 'foo:bar:baz' will return data['foo']['bar']['baz'] if this value exists, and will otherwise return ...
Traverse a dict or list using a colon-delimited (or otherwise delimited, using the 'delimiter' param) target string. The target 'foo:bar:0' will return data['foo']['bar'][0] if this value exists, and will otherwise return the dict in the default argument. Function will automatically determine the target...
def traverse_dict_and_list(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM): ''' Traverse a dict or list using a colon-delimited (or otherwise delimited, using the 'delimiter' param) target string. The target 'foo:bar:0' will return data['foo']['bar'][0] if this value exists, and will otherwise ...
Check for a match in a dictionary using a delimiter character to denote levels of subdicts, and also allowing the delimiter character to be matched. Thus, 'foo:bar:baz' will match data['foo'] == 'bar:baz' and data['foo']['bar'] == 'baz'. The latter would take priority over the former, as more deeply-nes...
def subdict_match(data, expr, delimiter=DEFAULT_TARGET_DELIM, regex_match=False, exact_match=False): ''' Check for a match in a dictionary using a delimiter character to denote levels of subdicts, and also allowing the delimiter charact...
Returns True if data is a list of one-element dicts (as found in many SLS schemas), otherwise returns False
def is_dictlist(data): ''' Returns True if data is a list of one-element dicts (as found in many SLS schemas), otherwise returns False ''' if isinstance(data, list): for element in data: if isinstance(element, dict): if len(element) != 1: retur...
Takes a list of one-element dicts (as found in many SLS schemas) and repacks into a single dictionary.
def repack_dictlist(data, strict=False, recurse=False, key_cb=None, val_cb=None): ''' Takes a list of one-element dicts (as found in many SLS schemas) and repacks into a single dictionary. ''' if isinstance(data, six.str...
Test if an object is iterable, but not a string type. Test if an object is an iterator or is iterable itself. By default this does not return True for string objects. The `ignore` argument defaults to a list of string types that are not considered iterable. This can be used to also exclude things like...
def is_iter(y, ignore=six.string_types): ''' Test if an object is iterable, but not a string type. Test if an object is an iterator or is iterable itself. By default this does not return True for string objects. The `ignore` argument defaults to a list of string types that are not considered i...
Returns a boolean value representing the "truth" of the value passed. The rules for what is a "True" value are: 1. Integer/float values greater than 0 2. The string values "True" and "true" 3. Any object for which bool(obj) returns True
def is_true(value=None): ''' Returns a boolean value representing the "truth" of the value passed. The rules for what is a "True" value are: 1. Integer/float values greater than 0 2. The string values "True" and "true" 3. Any object for which bool(obj) returns True ''' # Fir...
Convert MySQL-style output to a python dictionary
def mysql_to_dict(data, key): ''' Convert MySQL-style output to a python dictionary ''' ret = {} headers = [''] for line in data: if not line: continue if line.startswith('+'): continue comps = line.split('|') for comp in range(len(comps)):...
Convert the data list, dictionary into simple types, i.e., int, float, string, bool, etc.
def simple_types_filter(data): ''' Convert the data list, dictionary into simple types, i.e., int, float, string, bool, etc. ''' if data is None: return data simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool) simpletypes_values = tuple(list(simplety...
Given an iterable, returns its items as a list, with any non-string items converted to unicode strings.
def stringify(data): ''' Given an iterable, returns its items as a list, with any non-string items converted to unicode strings. ''' ret = [] for item in data: if six.PY2 and isinstance(item, str): item = salt.utils.stringutils.to_unicode(item) elif not isinstance(ite...
Query data using JMESPath language (http://jmespath.org).
def json_query(data, expr): ''' Query data using JMESPath language (http://jmespath.org). ''' if jmespath is None: err = 'json_query requires jmespath module installed' log.error(err) raise RuntimeError(err) return jmespath.search(expr, data)
Helper function for filter_falsey to determine if something is not to be considered falsey. :param any value: The value to consider :param list ignore_types: The types to ignore when considering the value. :return bool
def _is_not_considered_falsey(value, ignore_types=()): ''' Helper function for filter_falsey to determine if something is not to be considered falsey. :param any value: The value to consider :param list ignore_types: The types to ignore when considering the value. :return bool ''' retu...
Helper function to remove items from an iterable with falsey value. Removes ``None``, ``{}`` and ``[]``, 0, '' (but does not remove ``False``). Recurses into sub-iterables if ``recurse`` is set to ``True``. :param dict/list data: Source iterable (dict, OrderedDict, list, set, ...) to process. :param in...
def filter_falsey(data, recurse_depth=None, ignore_types=()): ''' Helper function to remove items from an iterable with falsey value. Removes ``None``, ``{}`` and ``[]``, 0, '' (but does not remove ``False``). Recurses into sub-iterables if ``recurse`` is set to ``True``. :param dict/list data: Sou...
Returns a generator iterating over keys and values, with the keys all being lowercase.
def items_lower(self): ''' Returns a generator iterating over keys and values, with the keys all being lowercase. ''' return ((key, val[1]) for key, val in six.iteritems(self._data))
Write a default to the system name The key of the given domain to write to domain The name of the domain to write to value The value to write to the given key vtype The type of value to be written, valid types are string, data, int[eger], float, bool[ean], dat...
def write(name, domain, value, vtype='string', user=None): ''' Write a default to the system name The key of the given domain to write to domain The name of the domain to write to value The value to write to the given key vtype The type of value to be written,...
Make sure the defaults value is absent name The key of the given domain to remove domain The name of the domain to remove from user The user to write the defaults to
def absent(name, domain, user=None): ''' Make sure the defaults value is absent name The key of the given domain to remove domain The name of the domain to remove from user The user to write the defaults to ''' ret = {'name': name, 'result': True, ...
Return information for the specified user This is just returns dummy data so that salt states can work. :param str name: The name of the user account to show. CLI Example: .. code-block:: bash salt '*' shadow.info root
def info(name): ''' Return information for the specified user This is just returns dummy data so that salt states can work. :param str name: The name of the user account to show. CLI Example: .. code-block:: bash salt '*' shadow.info root ''' info = __salt__['user.info'](name...
Converts the dotted notation of a saltclass class to its possible file counterparts. :param str _class: Dotted notation of the class :param str saltclass_path: Root to saltclass storage :return: 3-tuple of possible file counterparts :rtype: tuple(str)
def get_class_paths(_class, saltclass_path): ''' Converts the dotted notation of a saltclass class to its possible file counterparts. :param str _class: Dotted notation of the class :param str saltclass_path: Root to saltclass storage :return: 3-tuple of possible file counterparts :rtype: tuple...
Converts the absolute path to a saltclass file back to the dotted notation. .. code-block:: python print(get_class_from_file('/srv/saltclass/classes/services/nginx/init.yml', '/srv/saltclass')) # services.nginx :param str _file: Absolute path to file :param str saltclass_path: Root to saltc...
def get_class_from_file(_file, saltclass_path): ''' Converts the absolute path to a saltclass file back to the dotted notation. .. code-block:: python print(get_class_from_file('/srv/saltclass/classes/services/nginx/init.yml', '/srv/saltclass')) # services.nginx :param str _file: Absolu...
Takes a class name possibly including `*` or `?` wildcards (or any other wildcards supportet by `glob.glob`) and returns a list of expanded class names without wildcards. .. code-block:: python classes = match_class_glob('services.*', '/srv/saltclass') print(classes) # services.mariadb ...
def match_class_glob(_class, saltclass_path): ''' Takes a class name possibly including `*` or `?` wildcards (or any other wildcards supportet by `glob.glob`) and returns a list of expanded class names without wildcards. .. code-block:: python classes = match_class_glob('services.*', '/srv/salt...
Expand the list of `classes` to no longer include any globbing. :param iterable(str) classes: Iterable of classes :param dict salt_data: configuration data :return: Expanded list of classes with resolved globbing :rtype: list(str)
def expand_classes_glob(classes, salt_data): ''' Expand the list of `classes` to no longer include any globbing. :param iterable(str) classes: Iterable of classes :param dict salt_data: configuration data :return: Expanded list of classes with resolved globbing :rtype: list(str) ''' all...
Returns True, if the given parameter value is an instance of either int, str, float or bool.
def _is_simple_type(value): ''' Returns True, if the given parameter value is an instance of either int, str, float or bool. ''' return isinstance(value, six.string_types) or isinstance(value, int) or isinstance(value, float) or isinstance(value, bool)
Returns the type, id and option of a configuration object.
def _get_type_id_options(name, configuration): ''' Returns the type, id and option of a configuration object. ''' # it's in a form of source.name if '.' in name: type_, sep, id_ = name.partition('.') options = configuration else: type_ = next(six.iterkeys(configuration)) ...
Returns the only one key and it's value from a dictionary.
def _expand_one_key_dictionary(_dict): ''' Returns the only one key and it's value from a dictionary. ''' key = next(six.iterkeys(_dict)) value = _dict[key] return key, value