INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return the apf location
def __apf_cmd(cmd): ''' Return the apf location ''' apf_cmd = '{0} {1}'.format(salt.utils.path.which('apf'), cmd) out = __salt__['cmd.run_all'](apf_cmd) if out['retcode'] != 0: if not out['stderr']: msg = out['stdout'] else: msg = out['stderr'] ra...
Return True if apf is running otherwise return False
def _status_apf(): ''' Return True if apf is running otherwise return False ''' status = 0 table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: if 'sanity' in chain.name.lower(): status = 1 return True if status else False
Test to see if the vendor directory exists in this directory
def did_composer_install(dir): ''' Test to see if the vendor directory exists in this directory dir Directory location of the composer.json file CLI Example: .. code-block:: bash salt '*' composer.did_composer_install /var/www/application ''' lockFile = "{0}/vendor".forma...
Run PHP s composer with a specific action.
def _run_composer(action, directory=None, composer=None, php=None, runas=None, prefer_source=None, prefer_dist=None, no_scripts=None, no_plugins=None, optimiz...
Install composer dependencies for a directory.
def install(directory, composer=None, php=None, runas=None, prefer_source=None, prefer_dist=None, no_scripts=None, no_plugins=None, optimize=None, no_dev=None, quiet=False, composer_home='...
Update composer itself.
def selfupdate(composer=None, php=None, runas=None, quiet=False, composer_home='/root'): ''' Update composer itself. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` pa...
Sync all custom types
def sync_all(saltenv='base', extmod_whitelist=None, extmod_blacklist=None): ''' Sync all custom types saltenv : base The fileserver environment from which to sync. To sync from more than one environment, pass a comma-separated list. extmod_whitelist : None dictionary of modules...
Sync execution modules from salt:// _auth to the master
def sync_auth(saltenv='base', extmod_whitelist=None, extmod_blacklist=None): ''' Sync execution modules from ``salt://_auth`` to the master saltenv : base The fileserver environment from which to sync. To sync from more than one environment, pass a comma-separated list. extmod_whitelis...
Return available Packet os images.
def avail_images(call=None): ''' Return available Packet os images. CLI Example: .. code-block:: bash salt-cloud --list-images packet-provider salt-cloud -f avail_images packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_images fu...
Return available Packet datacenter locations.
def avail_locations(call=None): ''' Return available Packet datacenter locations. CLI Example: .. code-block:: bash salt-cloud --list-locations packet-provider salt-cloud -f avail_locations packet-provider ''' if call == 'action': raise SaltCloudException( ...
Return available Packet sizes.
def avail_sizes(call=None): ''' Return available Packet sizes. CLI Example: .. code-block:: bash salt-cloud --list-sizes packet-provider salt-cloud -f avail_sizes packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_locations functi...
Return available Packet projects.
def avail_projects(call=None): ''' Return available Packet projects. CLI Example: .. code-block:: bash salt-cloud -f avail_projects packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_projects function must be called with -f or --function....
Wait for a certain status from Packet. status_type device or volume object_id The ID of the Packet device or volume to wait on. Required. status The status to wait for. timeout The amount of time to wait for a status to update. quiet Log status updates to debug logs when False. Otherwise logs to info.
def _wait_for_status(status_type, object_id, status=None, timeout=500, quiet=True): ''' Wait for a certain status from Packet. status_type device or volume object_id The ID of the Packet device or volume to wait on. Required. status The status to wait for. timeout ...
Create a single Packet VM.
def create(vm_): ''' Create a single Packet VM. ''' name = vm_['name'] if not is_profile_configured(vm_): return False __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(name), args=__utils__['cloud.filter_event']...
List devices with all available information.
def list_nodes_full(call=None): ''' List devices, with all available information. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud -f list_nodes_full packet-provider .. ''' if call == 'action': raise SaltCloudException( ...
Return a list of the VMs that are on the provider. Only a list of VM names and their state is returned. This is the minimum amount of information needed to check for existing VMs.
def list_nodes_min(call=None): ''' Return a list of the VMs that are on the provider. Only a list of VM names and their state is returned. This is the minimum amount of information needed to check for existing VMs. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt...
Returns a list of devices keeping only a brief listing. CLI Example:.. code - block:: bash salt - cloud - Q salt - cloud -- query salt - cloud - f list_nodes packet - provider..
def list_nodes(call=None): ''' Returns a list of devices, keeping only a brief listing. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud -f list_nodes packet-provider .. ''' if call == 'action': raise SaltCloudException( ...
Destroys a Packet device by name.
def destroy(name, call=None): ''' Destroys a Packet device by name. name The hostname of VM to be be destroyed. CLI Example: .. code-block:: bash salt-cloud -d name ''' if call == 'function': raise SaltCloudException( 'The destroy action must be called...
Poll imgadm and compare available images
def beacon(config): ''' Poll imgadm and compare available images ''' ret = [] # NOTE: lookup current images current_images = __salt__['imgadm.list'](verbose=True) # NOTE: apply configuration if IMGADM_STATE['first_run']: log.info('Applying configuration for imgadm beacon') ...
Optionally mock a decorator that takes parameters
def mock_decorator_with_params(*oargs, **okwargs): # pylint: disable=unused-argument ''' Optionally mock a decorator that takes parameters E.g.: @blah(stuff=True) def things(): pass ''' def inner(fn, *iargs, **ikwargs): # pylint: disable=unused-argument if hasattr(fn, '__...
Ensures that the named command is not running.
def absent(name, user=None, signal=None): ''' Ensures that the named command is not running. name The pattern to match. user The user to which the process belongs signal Signal to send to the process(es). ''' ret = {'name': name, 'changes': {}, ...
Query NetBox API for minion data
def ext_pillar(minion_id, pillar, *args, **kwargs): ''' Query NetBox API for minion data ''' if minion_id == '*': log.info('There\'s no data to collect from NetBox for the Master') return {} # Pull settings from kwargs api_url = kwargs['api_url'].rstrip('/') api_token = kwarg...
Run the command configured
def top(**kwargs): ''' Run the command configured ''' if 'id' not in kwargs['opts']: return {} cmd = '{0} {1}'.format( __opts__['master_tops']['ext_nodes'], kwargs['opts']['id'] ) ndata = salt.utils.yaml.safe_load( subprocess.Popen( ...
Check the current value with the passed value
def _check_current_value(gnome_kwargs, value): ''' Check the current value with the passed value ''' current_value = __salt__['gnome.get'](**gnome_kwargs) return six.text_type(current_value) == six.text_type(value)
worker function for the others to use this handles all the gsetting magic
def _do(name, gnome_kwargs, preferences): ''' worker function for the others to use this handles all the gsetting magic ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} messages = [] for pref in preferences: key = pref ...
wm_preferences: sets values in the org. gnome. desktop. wm. preferences schema
def wm_preferences(name, user=None, action_double_click_titlebar=None, action_middle_click_titlebar=None, action_right_click_titlebar=None, application_based=None, audible_bell=None, auto...
desktop_lockdown: sets values in the org. gnome. desktop. lockdown schema
def desktop_lockdown(name, user=None, disable_application_handlers=None, disable_command_line=None, disable_lock_screen=None, disable_log_out=None, disable_print_setup=None, ...
desktop_interface: sets values in the org. gnome. desktop. interface schema
def desktop_interface(name, user=None, automatic_mnemonics=None, buttons_have_icons=None, can_change_accels=None, clock_format=None, clock_show_date=None, clock_show_...
Deserialize from TOML into Python data structure.
def deserialize(stream_or_string, **options): ''' Deserialize from TOML into Python data structure. :param stream_or_string: toml stream or string to deserialize. :param options: options given to lower pytoml module. ''' try: if not isinstance(stream_or_string, (bytes, six.string_types...
Serialize Python data to TOML.
def serialize(obj, **options): ''' Serialize Python data to TOML. :param obj: the data structure to serialize. :param options: options given to lower pytoml module. ''' try: if 'file_out' in options: return toml.dump(obj, options['file_out'], **options) else: ...
Render the template_file passing the functions and grains into the Mako rendering system.
def render(template_file, saltenv='base', sls='', context=None, tmplpath=None, **kws): ''' Render the template_file, passing the functions and grains into the Mako rendering system. :rtype: string ''' tmp_data = salt.utils.templates.MAKO(template_file, to_str=True, salt=__sa...
This function gets called when the proxy starts up. We check opts to see if a fallback user and password are supplied. If they are present and the primary credentials don t work then we try the backup before failing.
def init(opts): ''' This function gets called when the proxy starts up. We check opts to see if a fallback user and password are supplied. If they are present, and the primary credentials don't work, then we try the backup before failing. Whichever set of credentials works is placed in the pers...
Get the grains from the proxied device
def _grains(host, user, password): ''' Get the grains from the proxied device ''' r = __salt__['dracr.system_info'](host=host, admin_username=user, admin_password=password) if r.get('retcode', 0) == 0: GRAINS_CACHE =...
Cycle through all the possible credentials and return the first one that works
def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works ''' usernames = [__pillar__['proxy'].get('admin_username', 'root')] if 'fallback_admin_username' in __pillar__.get('proxy'): usernames.append(__pillar__['proxy'].get('fallback_admin...
This function is called by the: mod: salt. modules. chassis. cmd <salt. modules. chassis. cmd > shim. It then calls whatever is passed in cmd inside the: mod: salt. modules. dracr <salt. modules. dracr > module.
def chconfig(cmd, *args, **kwargs): ''' This function is called by the :mod:`salt.modules.chassis.cmd <salt.modules.chassis.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.dracr <salt.modules.dracr>` module. :param cmd: The command to call inside salt.modu...
Is the chassis responding?
def ping(): ''' Is the chassis responding? :return: Returns False if the chassis didn't respond, True otherwise. ''' r = __salt__['dracr.system_info'](host=DETAILS['host'], admin_username=DETAILS['admin_username'], admin_p...
Store a key value.
def store(bank, key, data): ''' Store a key value. ''' c_key = '{0}/{1}'.format(bank, key) try: c_data = __context__['serial'].dumps(data) api.kv.put(c_key, c_data) except Exception as exc: raise SaltCacheError( 'There was an error writing the key, {0}: {1}'.f...
Fetch a key value.
def fetch(bank, key): ''' Fetch a key value. ''' c_key = '{0}/{1}'.format(bank, key) try: _, value = api.kv.get(c_key) if value is None: return {} return __context__['serial'].loads(value['Value']) except Exception as exc: raise SaltCacheError( ...
Remove the key from the cache bank with all the key content.
def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. ''' if key is None: c_key = bank else: c_key = '{0}/{1}'.format(bank, key) try: return api.kv.delete(c_key, recurse=key is None) except Exception as exc: raise SaltCach...
Return an iterable object containing all entries stored in the specified bank.
def list_(bank): ''' Return an iterable object containing all entries stored in the specified bank. ''' try: _, keys = api.kv.get(bank + '/', keys=True, separator='/') except Exception as exc: raise SaltCacheError( 'There was an error getting the key "{0}": {1}'.format( ...
Checks if the specified bank contains the specified key.
def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' if key is None: return True # any key could be a branch and a leaf at the same time in Consul else: try: c_key = '{0}/{1}'.format(bank, key) _, value = api.kv.get(c_key)...
Sets a single pixel on the LED matrix to a specified color.
def set_pixel(x, y, color): ''' Sets a single pixel on the LED matrix to a specified color. x The x coordinate of the pixel. Ranges from 0 on the left to 7 on the right. y The y coordinate of the pixel. Ranges from 0 at the top to 7 at the bottom. color The new color of the ...
Displays a message on the LED matrix.
def show_message(message, msg_type=None, text_color=None, back_color=None, scroll_speed=0.1): ''' Displays a message on the LED matrix. message The message to display msg_type The type of the message. Changes the appearance of the message. Available types are:: ...
Displays a single letter on the LED matrix.
def show_letter(letter, text_color=None, back_color=None): ''' Displays a single letter on the LED matrix. letter The letter to display text_color The color in which the letter is shown. Defaults to '[255, 255, 255]' (white). back_color The background color of the display. D...
POST a payload
def _add(app, endpoint, payload): ''' POST a payload ''' nb = _nb_obj(auth_required=True) try: return getattr(getattr(nb, app), endpoint).create(**payload) except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False
Slugify given value. Credit to Djangoproject https:// docs. djangoproject. com/ en/ 2. 0/ _modules/ django/ utils/ text/ #slugify
def slugify(value): '''' Slugify given value. Credit to Djangoproject https://docs.djangoproject.com/en/2.0/_modules/django/utils/text/#slugify ''' value = re.sub(r'[^\w\s-]', '', value).strip().lower() return re.sub(r'[-\s]+', '-', value)
Helper function to do a GET request to Netbox. Returns the actual pynetbox object which allows manipulation from other functions.
def _get(app, endpoint, id=None, auth_required=False, **kwargs): ''' Helper function to do a GET request to Netbox. Returns the actual pynetbox object, which allows manipulation from other functions. ''' nb = _nb_obj(auth_required=auth_required) if id: item = getattr(getattr(nb, app), en...
Get a list of items from NetBox.
def filter_(app, endpoint, **kwargs): ''' Get a list of items from NetBox. app String of netbox app, e.g., ``dcim``, ``circuits``, ``ipam`` endpoint String of app endpoint, e.g., ``sites``, ``regions``, ``devices`` kwargs Optional arguments that can be used to filter. ...
Get a single item from NetBox.
def get_(app, endpoint, id=None, **kwargs): ''' Get a single item from NetBox. app String of netbox app, e.g., ``dcim``, ``circuits``, ``ipam`` endpoint String of app endpoint, e.g., ``sites``, ``regions``, ``devices`` Returns a single dictionary To get an item based on ID. ...
.. versionadded:: 2019. 2. 0
def create_manufacturer(name): ''' .. versionadded:: 2019.2.0 Create a device manufacturer. name The name of the manufacturer, e.g., ``Juniper`` CLI Example: .. code-block:: bash salt myminion netbox.create_manufacturer Juniper ''' nb_man = get_('dcim', 'manufacturer...
.. versionadded:: 2019. 2. 0
def create_device_type(model, manufacturer): ''' .. versionadded:: 2019.2.0 Create a device type. If the manufacturer doesn't exist, create a new manufacturer. model String of device model, e.g., ``MX480`` manufacturer String of device manufacturer, e.g., ``Juniper`` CLI Examp...
.. versionadded:: 2019. 2. 0
def create_device_role(role, color): ''' .. versionadded:: 2019.2.0 Create a device role role String of device role, e.g., ``router`` CLI Example: .. code-block:: bash salt myminion netbox.create_device_role router ''' nb_role = get_('dcim', 'device-roles', name=role...
.. versionadded:: 2019. 2. 0
def create_platform(platform): ''' .. versionadded:: 2019.2.0 Create a new device platform platform String of device platform, e.g., ``junos`` CLI Example: .. code-block:: bash salt myminion netbox.create_platform junos ''' nb_platform = get_('dcim', 'platforms', slu...
.. versionadded:: 2019. 2. 0
def create_site(site): ''' .. versionadded:: 2019.2.0 Create a new device site site String of device site, e.g., ``BRU`` CLI Example: .. code-block:: bash salt myminion netbox.create_site BRU ''' nb_site = get_('dcim', 'sites', name=site) if nb_site: retu...
.. versionadded:: 2019. 2. 0
def create_device(name, role, model, manufacturer, site): ''' .. versionadded:: 2019.2.0 Create a new device with a name, role, model, manufacturer and site. All these components need to be already in Netbox. name The ...
.. versionadded:: 2019. 2. 0
def update_device(name, **kwargs): ''' .. versionadded:: 2019.2.0 Add attributes to an existing device, identified by name. name The name of the device, e.g., ``edge_router`` kwargs Arguments to change in device, e.g., ``serial=JN2932930`` CLI Example: .. code-block:: bash...
.. versionadded:: 2019. 2. 0
def create_inventory_item(device_name, item_name, manufacturer_name=None, serial='', part_id='', description=''): ''' .. versionadded:: 2019.2.0 Add an inventory item to an exis...
.. versionadded:: 2019. 2. 0
def delete_inventory_item(item_id): ''' .. versionadded:: 2019.2.0 Remove an item from a devices inventory. Identified by the netbox id item_id Integer of item to be deleted CLI Example: .. code-block:: bash salt myminion netbox.delete_inventory_item 1354 ''' nb_inve...
.. versionadded:: 2019. 2. 0
def create_interface_connection(interface_a, interface_b): ''' .. versionadded:: 2019.2.0 Create an interface connection between 2 interfaces interface_a Interface id for Side A interface_b Interface id for Side B CLI Example: .. code-block:: bash salt myminion n...
.. versionadded:: 2019. 2. 0
def get_interfaces(device_name=None, **kwargs): ''' .. versionadded:: 2019.2.0 Returns interfaces for a specific device using arbitrary netbox filters device_name The name of the device, e.g., ``edge_router`` kwargs Optional arguments to be used for filtering CLI Example: ...
.. versionadded:: 2019. 2. 0
def openconfig_interfaces(device_name=None): ''' .. versionadded:: 2019.2.0 Return a dictionary structured as standardised in the `openconfig-interfaces <http://ops.openconfig.net/branches/master/openconfig-interfaces.html>`_ YANG model, containing physical and configuration data available in Netbo...
.. versionadded:: 2019. 2. 0
def openconfig_lacp(device_name=None): ''' .. versionadded:: 2019.2.0 Return a dictionary structured as standardised in the `openconfig-lacp <http://ops.openconfig.net/branches/master/openconfig-lacp.html>`_ YANG model, with configuration data for Link Aggregation Control Protocol (LACP) for ag...
.. versionadded:: 2019. 2. 0
def create_interface(device_name, interface_name, mac_address=None, description=None, enabled=None, lag=None, lag_parent=None, form_factor=None): ''' .. versionadded...
.. versionadded:: 2019. 2. 0
def update_interface(device_name, interface_name, **kwargs): ''' .. versionadded:: 2019.2.0 Update an existing interface with new attributes. device_name The name of the device, e.g., ``edge_router`` interface_name The name of the interface, e.g., ``ae13`` kwargs Argume...
.. versionadded:: 2019. 2. 0
def delete_interface(device_name, interface_name): ''' .. versionadded:: 2019.2.0 Delete an interface from a device. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface, e.g., ``ae13`` CLI Example: .. code-block:: bash ...
.. versionadded:: 2019. 2. 0
def make_interface_child(device_name, interface_name, parent_name): ''' .. versionadded:: 2019.2.0 Set an interface as part of a LAG. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``. ...
.. versionadded:: 2019. 2. 0
def create_ipaddress(ip_address, family, device=None, interface=None): ''' .. versionadded:: 2019.2.0 Add an IP address, and optionally attach it to an interface. ip_address The IP address and CIDR, e.g., ``192.168.1.1/24`` family Integer of IP family, e.g., ``4`` device ...
.. versionadded:: 2019. 2. 0
def delete_ipaddress(ipaddr_id): ''' .. versionadded:: 2019.2.0 Delete an IP address. IP addresses in Netbox are a combination of address and the interface it is assigned to. id The Netbox id for the IP address. CLI Example: .. code-block:: bash salt myminion netbox.dele...
.. versionadded:: 2019. 2. 0
def create_circuit_provider(name, asn=None): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit provider name The name of the circuit provider asn The ASN of the circuit provider CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_provid...
.. versionadded:: 2019. 2. 0
def get_circuit_provider(name, asn=None): ''' .. versionadded:: 2019.2.0 Get a circuit provider with a given name and optional ASN. name The name of the circuit provider asn The ASN of the circuit provider CLI Example: .. code-block:: bash salt myminion netbox.ge...
.. versionadded:: 2019. 2. 0
def create_circuit_type(name): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit type. name The name of the circuit type CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_type Transit ''' nb_circuit_type = get_('circuits', 'circuit-types'...
.. versionadded:: 2019. 2. 0
def create_circuit(name, provider_id, circuit_type, description=None): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit name Name of the circuit provider_id The netbox id of the circuit provider circuit_type The name of the circuit type asn The ASN...
.. versionadded:: 2019. 2. 0
def create_circuit_termination(circuit, interface, device, speed, xconnect_id=None, term_side='A'): ''' .. versionadded:: 2019.2.0 Terminate a circuit on an interface circuit The name of the circuit interface The name of the interface to terminate on device The name of ...
Return the requested value from the aws_kms key in salt configuration.
def _cfg(key, default=None): ''' Return the requested value from the aws_kms key in salt configuration. If it's not set, return the default. ''' root_cfg = __salt__.get('config.get', __opts__.get) kms_cfg = root_cfg('aws_kms', {}) return kms_cfg.get(key, default)
Return the boto3 session to use for the KMS client.
def _session(): ''' Return the boto3 session to use for the KMS client. If aws_kms:profile_name is set in the salt configuration, use that profile. Otherwise, fall back on the default aws profile. We use the boto3 profile system to avoid having to duplicate individual boto3 configuration setti...
Return the response dictionary from the KMS decrypt API call.
def _api_decrypt(): ''' Return the response dictionary from the KMS decrypt API call. ''' kms = _kms() data_key = _cfg_data_key() try: return kms.decrypt(CiphertextBlob=data_key) except botocore.exceptions.ClientError as orig_exc: error_code = orig_exc.response.get('Error', {...
Return the configured KMS data key decrypted and encoded in urlsafe base64.
def _plaintext_data_key(): ''' Return the configured KMS data key decrypted and encoded in urlsafe base64. Cache the result to minimize API calls to AWS. ''' response = getattr(_plaintext_data_key, 'response', None) cache_hit = response is not None if not cache_hit: response = _api_...
Given a blob of ciphertext as a bytestring try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted log the error and return the ciphertext back out.
def _decrypt_ciphertext(cipher, translate_newlines=False): ''' Given a blob of ciphertext as a bytestring, try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted, log the error, and return the ciphertext back out. ''' if translate_newlines: cipher = ...
Recursively try to decrypt any object. Recur on objects that are not strings. Decrypt strings that are valid Fernet tokens. Return the rest unchanged.
def _decrypt_object(obj, translate_newlines=False): ''' Recursively try to decrypt any object. Recur on objects that are not strings. Decrypt strings that are valid Fernet tokens. Return the rest unchanged. ''' if salt.utils.stringio.is_readable(obj): return _decrypt_object(obj.getva...
Decrypt the data to be rendered that was encrypted using AWS KMS envelope encryption.
def render(data, saltenv='base', sls='', argline='', **kwargs): # pylint: disable=unused-argument ''' Decrypt the data to be rendered that was encrypted using AWS KMS envelope encryption. ''' translate_newlines = kwargs.get('translate_newlines', False) return _decrypt_object(data, translate_newline...
Replaces the last 1/ 4 of a string with X s
def _serial_sanitizer(instr): '''Replaces the last 1/4 of a string with X's''' length = len(instr) index = int(math.floor(length * .75)) return '{0}{1}'.format(instr[:index], 'X' * (length - index))
Attempt to retrieve the named value from grains if the named value is not available return the passed default. The default return is an empty string.
def get(key, default='', delimiter=DEFAULT_TARGET_DELIM, ordered=True): ''' Attempt to retrieve the named value from grains, if the named value is not available return the passed default. The default return is an empty string. The value can also represent a value in a nested dict using a ":" delimiter ...
Determine whether a key exists in the grains dictionary.
def has_value(key): ''' Determine whether a key exists in the grains dictionary. Given a grains dictionary that contains the following structure:: {'pkg': {'apache': 'httpd'}} One would determine if the apache key in the pkg dict exists by:: pkg:apache CLI Example: .. code-...
Return all of the minion s grains
def items(sanitize=False): ''' Return all of the minion's grains CLI Example: .. code-block:: bash salt '*' grains.items Sanitized CLI Example: .. code-block:: bash salt '*' grains.items sanitize=True ''' if salt.utils.data.is_true(sanitize): out = dict(__gr...
Return one or more grains
def item(*args, **kwargs): ''' Return one or more grains CLI Example: .. code-block:: bash salt '*' grains.item os salt '*' grains.item os osrelease oscodename Sanitized CLI Example: .. code-block:: bash salt '*' grains.item host sanitize=True ''' ret = {} ...
Set new grains values in the grains config file
def setvals(grains, destructive=False): ''' Set new grains values in the grains config file destructive If an operation results in a key being removed, delete the key, too. Defaults to False. CLI Example: .. code-block:: bash salt '*' grains.setvals "{'key1': 'val1', 'key...
.. versionadded:: 0. 17. 0
def append(key, val, convert=False, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.17.0 Append a value to a list in the grains config file. If the grain doesn't exist, the grain key is added and the value is appended to the new grain as a list item. key The grain key to be ap...
.. versionadded:: 0. 17. 0
def remove(key, val, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.17.0 Remove a value from a list in the grains config file key The grain key to remove. val The value to remove. delimiter The key can be a nested dict key. Use this parameter to spec...
.. versionadded:: 0. 17. 0
def filter_by(lookup_dict, grain='os_family', merge=None, default='default', base=None): ''' .. versionadded:: 0.17.0 Look up the given grain in a given dictionary for the current OS and return the result Although this may occasionally be useful at the CLI, the primary intent of this function ...
Given a lookup string in the form of foo: bar: baz return a nested dictionary of the appropriate depth with the final segment as a value.
def _dict_from_path(path, val, delimiter=DEFAULT_TARGET_DELIM): ''' Given a lookup string in the form of 'foo:bar:baz" return a nested dictionary of the appropriate depth with the final segment as a value. >>> _dict_from_path('foo:bar:baz', 'somevalue') {"foo": {"bar": {"baz": "somevalue"}} '''...
Perform a one - time generation of a hash and write it to the local grains. If that grain has already been set return the value instead.
def get_or_set_hash(name, length=8, chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'): ''' Perform a one-time generation of a hash and write it to the local grains. If that grain has already been set return the value instead. This is useful for generating passwords or keys tha...
Set a key to an arbitrary value. It is used like setval but works with nested keys.
def set(key, val='', force=False, destructive=False, delimiter=DEFAULT_TARGET_DELIM): ''' Set a key to an arbitrary value. It is used like setval but works with nested keys. This function is conservative. It will only overwrite an entry if its value and the given one...
Used to make sure the minion s grain key/ value matches.
def equals(key, value): ''' Used to make sure the minion's grain key/value matches. Returns ``True`` if matches otherwise ``False``. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' grains.equals fqdn <expected_fqdn> salt '*' grains.equals systemd:versio...
Get a session to XenAPI. By default use the local UNIX socket.
def _get_xapi_session(): ''' Get a session to XenAPI. By default, use the local UNIX socket. ''' _xenapi = _check_xenapi() xapi_uri = __salt__['config.option']('xapi.uri') xapi_login = __salt__['config.option']('xapi.login') xapi_password = __salt__['config.option']('xapi.password') if...
Internal returns xl or xm command line path
def _get_xtool(): ''' Internal, returns xl or xm command line path ''' for xtool in ['xl', 'xm']: path = salt.utils.path.which(xtool) if path is not None: return path
Internal returns label s uuid
def _get_label_uuid(xapi, rectype, label): ''' Internal, returns label's uuid ''' try: return getattr(xapi, rectype).get_by_name_label(label)[0] except Exception: return False
Internal returns a full record for uuid
def _get_record_by_label(xapi, rectype, label): ''' Internal, returns a full record for uuid ''' uuid = _get_label_uuid(xapi, rectype, label) if uuid is False: return False return getattr(xapi, rectype).get_record(uuid)
Internal returns metrics record for a rectype
def _get_metrics_record(xapi, rectype, record): ''' Internal, returns metrics record for a rectype ''' metrics_id = record['metrics'] return getattr(xapi, '{0}_metrics'.format(rectype)).get_record(metrics_id)
Internal get value from record
def _get_val(record, keys): ''' Internal, get value from record ''' data = record for key in keys: if key in data: data = data[key] else: return None return data
Return a list of virtual machine names on the minion
def list_domains(): ''' Return a list of virtual machine names on the minion CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' with _get_xapi_session() as xapi: hosts = xapi.VM.get_all() ret = [] for _host in hosts: if xapi.VM.get_re...