INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Edit LXC configuration options path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion lxc.update_lxc_conf ubuntu \\ lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\...
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None): ''' Edit LXC configuration options path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion lxc.update_lxc_c...
.. versionchanged:: 2015.5.0 The ``dnsservers`` and ``searchdomains`` parameters can now be passed as a comma-separated list. Update /etc/resolv.confo path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example:...
def set_dns(name, dnsservers=None, searchdomains=None, path=None): ''' .. versionchanged:: 2015.5.0 The ``dnsservers`` and ``searchdomains`` parameters can now be passed as a comma-separated list. Update /etc/resolv.confo path path to the container parent default: /var...
Determine if systemD is running path path to the container parent .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.running_systemd ubuntu
def running_systemd(name, cache=True, path=None): ''' Determine if systemD is running path path to the container parent .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.running_systemd ubuntu ''' k = 'lxc.systemd.test.{0}{1}'.format(name...
Get the operational state of a systemd based container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion lxc.systemd_running_state ubuntu
def systemd_running_state(name, path=None): ''' Get the operational state of a systemd based container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion lxc.systemd_...
Check that the system has fully inited This is actually very important for systemD based containers see https://github.com/saltstack/salt/issues/23847 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. cod...
def wait_started(name, path=None, timeout=300): ''' Check that the system has fully inited This is actually very important for systemD based containers see https://github.com/saltstack/salt/issues/23847 path path to the container parent default: /var/lib/lxc (system default) ...
Return True if the named container can be attached to via the lxc-attach command path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt 'minion' lxc.attachable ubuntu
def attachable(name, path=None): ''' Return True if the named container can be attached to via the lxc-attach command path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt 'm...
Common logic for lxc.run functions path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0
def _run(name, cmd, output=None, no_start=False, preserve_state=True, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, path=None, ignore_retcode=False, chroot_fallback=None, keep_env='http_pr...
.. versionadded:: 2015.8.0 Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container .. warning:: Many shell builtins do not work, failing with stderr similar to the following: .. code-block:: bash lxc_container: No such file or directory - failed to exec 'command'...
def run(name, cmd, no_start=False, preserve_state=True, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, path=None, ignore_retcode=False, chroot_fallback=False, keep_env='http_proxy,https_proxy,no_proxy'): '...
Get the MD5 checksum of a file from a container
def _get_md5(name, path): ''' Get the MD5 checksum of a file from a container ''' output = run_stdout(name, 'md5sum "{0}"'.format(path), chroot_fallback=True, ignore_retcode=True) try: return output.split()[0] except IndexError: # D...
.. versionchanged:: 2015.8.0 Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency with other container types. ``lxc.cp`` will continue to work, however. For versions 2015.2.x and earlier, use ``lxc.cp``. Copy a file or directory from the host into a container name ...
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None): ''' .. versionchanged:: 2015.8.0 Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency with other container types. ``lxc.cp`` will continue to work, however. For versions 2015.2.x and earlier, use ...
Read in an LXC configuration file. By default returns a simple, unsorted dict, but can also return a more detailed structure including blank lines and comments. out_format: set to 'simple' if you need the old and unsupported behavior. This won't support the multiple lxc values (eg: multiple...
def read_conf(conf_file, out_format='simple'): ''' Read in an LXC configuration file. By default returns a simple, unsorted dict, but can also return a more detailed structure including blank lines and comments. out_format: set to 'simple' if you need the old and unsupported behavior. ...
Write out an LXC configuration file This is normally only used internally. The format of the data structure must match that which is returned from ``lxc.read_conf()``, with ``out_format`` set to ``commented``. An example might look like: .. code-block:: python [ {'lxc.utsname...
def write_conf(conf_file, conf): ''' Write out an LXC configuration file This is normally only used internally. The format of the data structure must match that which is returned from ``lxc.read_conf()``, with ``out_format`` set to ``commented``. An example might look like: .. code-block:...
Edit an LXC configuration file. If a setting is already present inside the file, its value will be replaced. If it does not exist, it will be appended to the end of the file. Comments and blank lines will be kept in-tact if they already exist in the file. out_format: Set to simple if you need b...
def edit_conf(conf_file, out_format='simple', read_only=False, lxc_config=None, **kwargs): ''' Edit an LXC configuration file. If a setting is already present inside the file, its value will be replaced. If it does not exist, it will be appended to...
Reboot a container. path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt 'minion' lxc.reboot myvm
def reboot(name, path=None): ''' Reboot a container. path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt 'minion' lxc.reboot myvm ''' ret = {'result': True, ...
Reconfigure a container. This only applies to a few property name Name of the container. utsname utsname of the container. .. versionadded:: 2016.3.0 rootfs rootfs of the container. .. versionadded:: 2016.3.0 cpu Select a random number of cpu cor...
def reconfigure(name, cpu=None, cpuset=None, cpushare=None, memory=None, profile=None, network_profile=None, nic_opts=None, bridge=None, gateway=None, autostart...
.. versionadded:: 2015.5.0 Apply a network profile to a container network_profile profile name or default values (dict) nic_opts values to override in defaults (dict) indexed by nic card names path path to the container parent .. versionadded:: 2015.8.0 ...
def apply_network_profile(name, network_profile, nic_opts=None, path=None): ''' .. versionadded:: 2015.5.0 Apply a network profile to a container network_profile profile name or default values (dict) nic_opts values to override in defaults (dict) indexed by nic card names ...
Returns a container pid. Throw an exception if the container isn't running. CLI Example: .. code-block:: bash salt '*' lxc.get_pid name
def get_pid(name, path=None): ''' Returns a container pid. Throw an exception if the container isn't running. CLI Example: .. code-block:: bash salt '*' lxc.get_pid name ''' if name not in list_(limit='running', path=path): raise CommandExecutionError('Container {0} is not...
Removes parameters which match the pattern from the config data
def _filter_data(self, pattern): ''' Removes parameters which match the pattern from the config data ''' removed = [] filtered = [] for param in self.data: if not param[0].startswith(pattern): filtered.append(param) else: ...
Helper to return known serializer based on pass output argument
def _get_serializer(output): ''' Helper to return known serializer based on pass output argument ''' serializers = salt.loader.serializers(__opts__) try: return getattr(serializers, output) except AttributeError: raise CommandExecutionError( "Unknown serializer '{...
Parse stdout of a command and generate an event The script engine will scrap stdout of the given script and generate an event based on the presence of the 'tag' key and it's value. If there is a data obj available, that will also be fired along with the tag. Example: Given the follow...
def start(cmd, output='json', interval=1): ''' Parse stdout of a command and generate an event The script engine will scrap stdout of the given script and generate an event based on the presence of the 'tag' key and it's value. If there is a data obj available, that will also be fired alon...
Return Bluez version from bluetoothd -v CLI Example: .. code-block:: bash salt '*' bluetoothd.version
def version(): ''' Return Bluez version from bluetoothd -v CLI Example: .. code-block:: bash salt '*' bluetoothd.version ''' cmd = 'bluetoothctl -v' out = __salt__['cmd.run'](cmd).splitlines() bluez_version = out[0] pybluez_version = '<= 0.18 (Unknown, but installed)' ...
Get the many addresses of the Bluetooth adapter CLI Example: .. code-block:: bash salt '*' bluetooth.address
def address_(): ''' Get the many addresses of the Bluetooth adapter CLI Example: .. code-block:: bash salt '*' bluetooth.address ''' ret = {} cmd = 'hciconfig' out = __salt__['cmd.run'](cmd).splitlines() dev = '' for line in out: if line.startswith('hci'): ...
Power a bluetooth device on or off CLI Examples: .. code-block:: bash salt '*' bluetooth.power hci0 on salt '*' bluetooth.power hci0 off
def power(dev, mode): ''' Power a bluetooth device on or off CLI Examples: .. code-block:: bash salt '*' bluetooth.power hci0 on salt '*' bluetooth.power hci0 off ''' if dev not in address_(): raise CommandExecutionError('Invalid dev passed to bluetooth.power') if...
Enable this bluetooth device to be discoverable. CLI Example: .. code-block:: bash salt '*' bluetooth.discoverable hci0
def discoverable(dev): ''' Enable this bluetooth device to be discoverable. CLI Example: .. code-block:: bash salt '*' bluetooth.discoverable hci0 ''' if dev not in address_(): raise CommandExecutionError( 'Invalid dev passed to bluetooth.discoverable' ) ...
Scan for bluetooth devices in the area CLI Example: .. code-block:: bash salt '*' bluetooth.scan
def scan(): ''' Scan for bluetooth devices in the area CLI Example: .. code-block:: bash salt '*' bluetooth.scan ''' ret = [] devices = bluetooth.discover_devices(lookup_names=True) for device in devices: ret.append({device[0]: device[1]}) return ret
Block a specific bluetooth device by BD Address CLI Example: .. code-block:: bash salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
def block(bdaddr): ''' Block a specific bluetooth device by BD Address CLI Example: .. code-block:: bash salt '*' bluetooth.block DE:AD:BE:EF:CA:FE ''' if not salt.utils.validate.net.mac(bdaddr): raise CommandExecutionError( 'Invalid BD address passed to bluetooth....
Pair the bluetooth adapter with a device CLI Example: .. code-block:: bash salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234 Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234 is the passphrase. TODO: This function is currently broken, as the bluez-simple-agent pro...
def pair(address, key): ''' Pair the bluetooth adapter with a device CLI Example: .. code-block:: bash salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234 Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234 is the passphrase. TODO: This function is currently b...
Unpair the bluetooth adapter from a device CLI Example: .. code-block:: bash salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE Where DE:AD:BE:EF:CA:FE is the address of the device to unpair. TODO: This function is currently broken, as the bluez-simple-agent program no longer ships with BlueZ ...
def unpair(address): ''' Unpair the bluetooth adapter from a device CLI Example: .. code-block:: bash salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE Where DE:AD:BE:EF:CA:FE is the address of the device to unpair. TODO: This function is currently broken, as the bluez-simple-agent progra...
Send a message to an MS Teams channel. :param message: The message to send to the MS Teams channel. :param hook_url: The Teams webhook URL, if not specified in the configuration. :param title: Optional title for the posted card :param theme_color: Optional hex color highlight for the poste...
def post_card(message, hook_url=None, title=None, theme_color=None): ''' Send a message to an MS Teams channel. :param message: The message to send to the MS Teams channel. :param hook_url: The Teams webhook URL, if not specified in the configuration. ...
Scan for processes and fire events Example Config .. code-block:: yaml beacons: ps: - processes: salt-master: running mysql: stopped The config above sets up beacons to check that processes are running or stopped.
def beacon(config): ''' Scan for processes and fire events Example Config .. code-block:: yaml beacons: ps: - processes: salt-master: running mysql: stopped The config above sets up beacons to check that processes are running or s...
List the nodes, ask all 'vagrant' minions, return dict of grains.
def _list_nodes(call=None): ''' List the nodes, ask all 'vagrant' minions, return dict of grains. ''' local = salt.client.LocalClient() ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain') return ret
List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced). CLI Example: .. code-block:: bash salt-call -F
def list_nodes_full(call=None): ''' List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced). CLI Example: .. code-block:: bash salt-call -F ''' ret = _list_nodes(call) for key, grains in ret.items(): # clean up some hyperverbose grains -- everything is too mu...
Provision a single machine CLI Example: .. code-block:: bash salt-cloud -p my_profile new_node_1
def create(vm_): ''' Provision a single machine CLI Example: .. code-block:: bash salt-cloud -p my_profile new_node_1 ''' name = vm_['name'] machine = config.get_cloud_config_value( 'machine', vm_, __opts__, default='') vm_['machine'] = machine host = config.get_c...
Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine
def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud --destroy mymachine ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a, or --action.' ...
Reboot a vagrant minion. name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot vm_name
def reboot(name, call=None): ''' Reboot a vagrant minion. name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot vm_name ''' if call != 'action': raise SaltCloudException( 'The reboot action must be called with -a or ...
Remove the rtag file
def clear_rtag(opts): ''' Remove the rtag file ''' try: os.remove(rtag(opts)) except OSError as exc: if exc.errno != errno.ENOENT: # Using __str__() here to get the fully-formatted error message # (error number, error message, path) log.warning('En...
Write the rtag file
def write_rtag(opts): ''' Write the rtag file ''' rtag_file = rtag(opts) if not os.path.exists(rtag_file): try: with salt.utils.files.fopen(rtag_file, 'w+'): pass except OSError as exc: log.warning('Encountered error writing rtag: %s', exc.__st...
Check whether or not a refresh is necessary Returns: - True if refresh evaluates as True - False if refresh is False - A boolean if refresh is not False and the rtag file exists
def check_refresh(opts, refresh=None): ''' Check whether or not a refresh is necessary Returns: - True if refresh evaluates as True - False if refresh is False - A boolean if refresh is not False and the rtag file exists ''' return bool( salt.utils.data.is_true(refresh) or ...
Returns the first version of the list of available versions which matches the desired version comparison expression, or None if no match is found.
def match_version(desired, available, cmp_func=None, ignore_epoch=False): ''' Returns the first version of the list of available versions which matches the desired version comparison expression, or None if no match is found. ''' oper, version = split_comparison(desired) if not oper: oper...
Set up openstack credentials
def _auth(profile=None): ''' Set up openstack credentials ''' if profile: credentials = __salt__['config.option'](profile) user = credentials['keystone.user'] password = credentials.get('keystone.password', None) tenant = credentials['keystone.tenant'] auth_url = ...
Delete a container, or delete an object from a container. CLI Example to delete a container:: salt myminion swift.delete mycontainer CLI Example to delete an object from a container:: salt myminion swift.delete mycontainer remoteobject
def delete(cont, path=None, profile=None): ''' Delete a container, or delete an object from a container. CLI Example to delete a container:: salt myminion swift.delete mycontainer CLI Example to delete an object from a container:: salt myminion swift.delete mycontainer remoteobject ...
List the contents of a container, or return an object from a container. Set return_bin to True in order to retrieve an object wholesale. Otherwise, Salt will attempt to parse an XML response. CLI Example to list containers: .. code-block:: bash salt myminion swift.get CLI Example to list...
def get(cont=None, path=None, local_file=None, return_bin=False, profile=None): ''' List the contents of a container, or return an object from a container. Set return_bin to True in order to retrieve an object wholesale. Otherwise, Salt will attempt to parse an XML response. CLI Example to list con...
Create a new container, or upload an object to a container. CLI Example to create a container: .. code-block:: bash salt myminion swift.put mycontainer CLI Example to upload an object to a container: .. code-block:: bash salt myminion swift.put mycontainer remotepath local_file=/pa...
def put(cont, path=None, local_file=None, profile=None): ''' Create a new container, or upload an object to a container. CLI Example to create a container: .. code-block:: bash salt myminion swift.put mycontainer CLI Example to upload an object to a container: .. code-block:: bash ...
Get the entire accountPolicy and return it as a dictionary. For use by this module only :param str name: The user name :return: a dictionary containing all values for the accountPolicy :rtype: dict :raises: CommandExecutionError on user not found or any other unknown error
def _get_account_policy(name): ''' Get the entire accountPolicy and return it as a dictionary. For use by this module only :param str name: The user name :return: a dictionary containing all values for the accountPolicy :rtype: dict :raises: CommandExecutionError on user not found or any ...
Set a value in the user accountPolicy. For use by this module only :param str name: The user name :param str policy: The policy to apply :return: True if success, otherwise False :rtype: bool :raises: CommandExecutionError on user not found or any other unknown error
def _set_account_policy(name, policy): ''' Set a value in the user accountPolicy. For use by this module only :param str name: The user name :param str policy: The policy to apply :return: True if success, otherwise False :rtype: bool :raises: CommandExecutionError on user not found or an...
Return the value for a key in the accountPolicy section of the user's plist file. For use by this module only :param str name: The username :param str key: The accountPolicy key :return: The value contained within the key :rtype: str :raises: CommandExecutionError on user not found or any oth...
def _get_account_policy_data_value(name, key): ''' Return the value for a key in the accountPolicy section of the user's plist file. For use by this module only :param str name: The username :param str key: The accountPolicy key :return: The value contained within the key :rtype: str ...
Converts a unix timestamp to a human readable date/time :param float unix_timestamp: A unix timestamp :return: A date/time in the format YYYY-mm-dd HH:MM:SS :rtype: str
def _convert_to_datetime(unix_timestamp): ''' Converts a unix timestamp to a human readable date/time :param float unix_timestamp: A unix timestamp :return: A date/time in the format YYYY-mm-dd HH:MM:SS :rtype: str ''' try: unix_timestamp = float(unix_timestamp) return date...
Return information for the specified user :param str name: The username :return: A dictionary containing the user's shadow information :rtype: dict CLI Example: .. code-block:: bash salt '*' shadow.info admin
def info(name): ''' Return information for the specified user :param str name: The username :return: A dictionary containing the user's shadow information :rtype: dict CLI Example: .. code-block:: bash salt '*' shadow.info admin ''' try: data = pwd.getpwnam(name)...
Get the date/time the account was created :param str name: The username of the account :return: The date/time the account was created (yyyy-mm-dd hh:mm:ss) :rtype: str :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-block:: bash salt...
def get_account_created(name): ''' Get the date/time the account was created :param str name: The username of the account :return: The date/time the account was created (yyyy-mm-dd hh:mm:ss) :rtype: str :raises: CommandExecutionError on user not found or any other unknown error CLI Examp...
Get the the number of failed login attempts :param str name: The username of the account :return: The number of failed login attempts :rtype: int :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-block:: bash salt '*' shadow.get_login_...
def get_login_failed_count(name): ''' Get the the number of failed login attempts :param str name: The username of the account :return: The number of failed login attempts :rtype: int :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-bl...
Set the maximum age of the password in days :param str name: The username of the account :param int days: The maximum age of the account in days :return: True if successful, False if not :rtype: bool :raises: CommandExecutionError on user not found or any other unknown error CLI Example: ...
def set_maxdays(name, days): ''' Set the maximum age of the password in days :param str name: The username of the account :param int days: The maximum age of the account in days :return: True if successful, False if not :rtype: bool :raises: CommandExecutionError on user not found or any...
Get the maximum age of the password :param str name: The username of the account :return: The maximum age of the password in days :rtype: int :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-block:: bash salt '*' shadow.get_maxdays ad...
def get_maxdays(name): ''' Get the maximum age of the password :param str name: The username of the account :return: The maximum age of the password in days :rtype: int :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-block:: bash ...
Sets the date on which the password expires. The user will be required to change their password. Format is mm/dd/yyyy :param str name: The name of the user account :param date date: The date the password will expire. Must be in mm/dd/yyyy format. :return: True if successful, otherwise False ...
def set_change(name, date): ''' Sets the date on which the password expires. The user will be required to change their password. Format is mm/dd/yyyy :param str name: The name of the user account :param date date: The date the password will expire. Must be in mm/dd/yyyy format. :retur...
Sets the date on which the account expires. The user will not be able to login after this date. Date format is mm/dd/yyyy :param str name: The name of the user account :param datetime date: The date the account will expire. Format must be mm/dd/yyyy. :return: True if successful, False if not ...
def set_expire(name, date): ''' Sets the date on which the account expires. The user will not be able to login after this date. Date format is mm/dd/yyyy :param str name: The name of the user account :param datetime date: The date the account will expire. Format must be mm/dd/yyyy. :r...
Deletes the account password :param str name: The user name of the account :return: True if successful, otherwise False :rtype: bool :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-block:: bash salt '*' shadow.del_password username
def del_password(name): ''' Deletes the account password :param str name: The user name of the account :return: True if successful, otherwise False :rtype: bool :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-block:: bash sal...
Set the password for a named user (insecure, the password will be in the process list while the command is running) :param str name: The name of the local user, which is assumed to be in the local directory service :param str password: The plaintext password to set :return: True if successful...
def set_password(name, password): ''' Set the password for a named user (insecure, the password will be in the process list while the command is running) :param str name: The name of the local user, which is assumed to be in the local directory service :param str password: The plaintext pa...
Ensure the RabbitMQ policy exists. Reference: http://www.rabbitmq.com/ha.html name Policy name pattern A regex of queues to apply the policy to definition A json dict describing the policy priority Priority (defaults to 0) vhost Virtual host to apply to ...
def present(name, pattern, definition, priority=0, vhost='/', runas=None, apply_to=None): ''' Ensure the RabbitMQ policy exists. Reference: http://www.rabbitmq.com/ha.html name Policy name pattern A regex of qu...
Ensure the named policy is absent Reference: http://www.rabbitmq.com/ha.html name The name of the policy to remove runas Name of the user to run the command as
def absent(name, vhost='/', runas=None): ''' Ensure the named policy is absent Reference: http://www.rabbitmq.com/ha.html name The name of the policy to remove runas Name of the user to run the command as ''' ret = {'name': name, 'result': True, 'comme...
Return the first configured instance.
def get_configured_provider(): ''' Return the first configured instance. ''' return config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('auth', 'region_name'), log_message=False, ) or config.is_provider_configured( __opts__, __active_provide...
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
def preferred_ip(vm_, ips): ''' Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'. ''' proto = config.get_cloud_config_value( 'protocol', vm_, __opts__, default='ipv4', search_global=False ) family = socket.AF_INET if proto == 'ipv6': family = socket....
Return a conn object for the passed VM data
def get_conn(): ''' Return a conn object for the passed VM data ''' if __active_provider_name__ in __context__: return __context__[__active_provider_name__] vm_ = get_configured_provider() profile = vm_.pop('profile', None) if profile is not None: vm_ = __utils__['dictupdate....
Return a list of VMs CLI Example .. code-block:: bash salt-cloud -f list_nodes myopenstack
def list_nodes(conn=None, call=None): ''' Return a list of VMs CLI Example .. code-block:: bash salt-cloud -f list_nodes myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) r...
Return a list of VMs with minimal information CLI Example .. code-block:: bash salt-cloud -f list_nodes_min myopenstack
def list_nodes_min(conn=None, call=None): ''' Return a list of VMs with minimal information CLI Example .. code-block:: bash salt-cloud -f list_nodes_min myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_min function must be called wi...
Return a list of VMs with all the information about them CLI Example .. code-block:: bash salt-cloud -f list_nodes_full myopenstack
def list_nodes_full(conn=None, call=None): ''' Return a list of VMs with all the information about them CLI Example .. code-block:: bash salt-cloud -f list_nodes_full myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function mus...
Return a list of VMs with the fields from `query.selection` CLI Example .. code-block:: bash salt-cloud -f list_nodes_full myopenstack
def list_nodes_select(conn=None, call=None): ''' Return a list of VMs with the fields from `query.selection` CLI Example .. code-block:: bash salt-cloud -f list_nodes_full myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_select funct...
Get VM on this OpenStack account name name of the instance CLI Example .. code-block:: bash salt-cloud -a show_instance myserver
def show_instance(name, conn=None, call=None): ''' Get VM on this OpenStack account name name of the instance CLI Example .. code-block:: bash salt-cloud -a show_instance myserver ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance...
List available images for OpenStack CLI Example .. code-block:: bash salt-cloud -f avail_images myopenstack salt-cloud --list-images myopenstack
def avail_images(conn=None, call=None): ''' List available images for OpenStack CLI Example .. code-block:: bash salt-cloud -f avail_images myopenstack salt-cloud --list-images myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_imag...
List available sizes for OpenStack CLI Example .. code-block:: bash salt-cloud -f avail_sizes myopenstack salt-cloud --list-sizes myopenstack
def avail_sizes(conn=None, call=None): ''' List available sizes for OpenStack CLI Example .. code-block:: bash salt-cloud -f avail_sizes myopenstack salt-cloud --list-sizes myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes fu...
List networks for OpenStack CLI Example .. code-block:: bash salt-cloud -f list_networks myopenstack
def list_networks(conn=None, call=None): ''' List networks for OpenStack CLI Example .. code-block:: bash salt-cloud -f list_networks myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The list_networks function must be called with ' '-f ...
List subnets in a virtual network network network to list subnets of .. code-block:: bash salt-cloud -f list_subnets myopenstack network=salt-net
def list_subnets(conn=None, call=None, kwargs=None): ''' List subnets in a virtual network network network to list subnets of .. code-block:: bash salt-cloud -f list_subnets myopenstack network=salt-net ''' if call == 'action': raise SaltCloudSystemExit( '...
Sanatize kwargs to be sent to create_server
def _clean_create_kwargs(**kwargs): ''' Sanatize kwargs to be sent to create_server ''' VALID_OPTS = { 'name': six.string_types, 'image': six.string_types, 'flavor': six.string_types, 'auto_ip': bool, 'ips': list, 'ip_pool': six.string_types, 'root...
Request an instance to be built
def request_instance(vm_, conn=None, call=None): ''' Request an instance to be built ''' if call == 'function': # Technically this function may be called other ways too, but it # definitely cannot be called with --function. raise SaltCloudSystemExit( 'The request_inst...
Create a single VM from a data dict
def create(vm_): ''' Create a single VM from a data dict ''' deploy = config.get_cloud_config_value('deploy', vm_, __opts__) key_filename = config.get_cloud_config_value( 'ssh_key_file', vm_, __opts__, search_global=False, default=None ) if key_filename is not None and not os.path.is...
Delete a single VM
def destroy(name, conn=None, call=None): ''' Delete a single VM ''' if call == 'function': raise SaltCloudSystemExit( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroy...
Call function from shade. func function to call from shade.openstackcloud library CLI Example .. code-block:: bash salt-cloud -f call myopenstack func=list_images t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
def call(conn=None, call=None, kwargs=None): ''' Call function from shade. func function to call from shade.openstackcloud library CLI Example .. code-block:: bash salt-cloud -f call myopenstack func=list_images t sujksalt-cloud -f call myopenstack func=create_network na...
Merge a data structure into another by choosing a merge strategy Strategies: * aggregate * list * overwrite * recurse * smart CLI Example: .. code-block:: shell salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False): ''' Merge a data structure into another by choosing a merge strategy Strategies: * aggregate * list * overwrite * recurse * smart CLI Example: .. code-block:: shell salt '*' slsutil.merge ...
.. versionadded:: 2019.2.0 Merge a list of objects into each other in order :type lst: Iterable :param lst: List of objects to be merged. :type strategy: String :param strategy: Merge strategy. See utils.dictupdate. :type renderer: String :param renderer: Renderer type. Used to d...
def merge_all(lst, strategy='smart', renderer='yaml', merge_lists=False): ''' .. versionadded:: 2019.2.0 Merge a list of objects into each other in order :type lst: Iterable :param lst: List of objects to be merged. :type strategy: String :param strategy: Merge strategy. See utils.dictupd...
Serialize a Python object using a :py:mod:`serializer module <salt.serializers>` CLI Example: .. code-block:: bash salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'} Jinja Example: .. code-block:: jinja {% set json_string = salt.slsutil.serialize('json', ...
def serialize(serializer, obj, **mod_kwargs): ''' Serialize a Python object using a :py:mod:`serializer module <salt.serializers>` CLI Example: .. code-block:: bash salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'} Jinja Example: .. code-block:: jinja ...
Deserialize a Python object using a :py:mod:`serializer module <salt.serializers>` CLI Example: .. code-block:: bash salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}' salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\ stream_or_string='{"foo": "Foo!"}' ...
def deserialize(serializer, stream_or_string, **mod_kwargs): ''' Deserialize a Python object using a :py:mod:`serializer module <salt.serializers>` CLI Example: .. code-block:: bash salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}' salt '*' --no-parse=stream_or_string slsutil....
.. versionadded:: 2015.8.0 Return a storage_conn object for the storage account
def get_storage_conn(storage_account=None, storage_key=None, opts=None): ''' .. versionadded:: 2015.8.0 Return a storage_conn object for the storage account ''' if opts is None: opts = {} if not storage_account: storage_account = opts.get('storage_account', None) if not sto...
Create a standardized comment block to include in a templated file. A common technique in configuration management is to include a comment block in managed files, warning users not to modify the file. This function simplifies and standardizes those comment blocks. :param width: The width, in character...
def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None, title=None, text=None, newline=False): ''' Create a standardized comment block to include in a templated file. A common technique in configuration management is to include a comment block in managed files, ...
.. versionadded:: 2015.8.0 List blobs associated with the container
def list_blobs(storage_conn=None, **kwargs): ''' .. versionadded:: 2015.8.0 List blobs associated with the container ''' if not storage_conn: storage_conn = get_storage_conn(opts=kwargs) if 'container' not in kwargs: raise SaltSystemExit( code=42, msg='A...
.. versionadded:: 2015.8.0 Upload a blob
def put_blob(storage_conn=None, **kwargs): ''' .. versionadded:: 2015.8.0 Upload a blob ''' if not storage_conn: storage_conn = get_storage_conn(opts=kwargs) if 'container' not in kwargs: raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container...
.. versionadded:: 2015.8.0 Download a blob
def get_blob(storage_conn=None, **kwargs): ''' .. versionadded:: 2015.8.0 Download a blob ''' if not storage_conn: storage_conn = get_storage_conn(opts=kwargs) if 'container' not in kwargs: raise SaltSystemExit(code=42, msg='The blob container name must be specified as "contain...
.. versionadded:: 2015.8.0 Convert an object to a dictionary
def object_to_dict(obj): ''' .. versionadded:: 2015.8.0 Convert an object to a dictionary ''' if isinstance(obj, list) or isinstance(obj, tuple): ret = [] for item in obj: ret.append(object_to_dict(item)) elif hasattr(obj, '__dict__'): ret = {} for it...
Execute the salt-cloud command line
def run(self): ''' Execute the salt-cloud command line ''' # Parse shell arguments self.parse_args() salt_master_user = self.config.get('user') if salt_master_user is None: salt_master_user = salt.utils.user.get_user() if not check_user(salt_...
Make sure the user is inside the specified htpasswd file name User name password User password htpasswd_file Path to the htpasswd file options See :mod:`salt.modules.htpasswd.useradd` force Touch the file even if user already created runas Th...
def user_exists(name, password=None, htpasswd_file=None, options='', force=False, runas=None, update=False): ''' Make sure the user is inside the specified htpasswd file name User name password User password htpasswd_file Path to the htpasswd file opti...
Make sure the user is not in the specified htpasswd file name User name htpasswd_file Path to the htpasswd file runas The system user to run htpasswd command with
def user_absent(name, htpasswd_file=None, runas=None): ''' Make sure the user is not in the specified htpasswd file name User name htpasswd_file Path to the htpasswd file runas The system user to run htpasswd command with ''' ret = {'name': name, 'chang...
Execute celery tasks. For celery specific parameters see celery documentation. CLI Example: .. code-block:: bash salt '*' celery.run_task tasks.sleep args=[4] broker=redis://localhost \\ backend=redis://localhost wait_for_result=true task_name The task name, e.g. tasks.sleep ...
def run_task(task_name, args=None, kwargs=None, broker=None, backend=None, wait_for_result=False, timeout=None, propagate=True, interval=0.5, no_ack=True, raise_timeout=True, config=None): ''' Execute celery tasks. For celery specific parameters see celery documentation. CLI Example: .. ...
Execute the salt command given by cmd dict. cmd is a dictionary of the following form: { 'mode': 'modestring', 'fun' : 'modulefunctionstring', 'kwarg': functionkeywordargdictionary, 'tgt' : 'targetpatternstring', 'tgt_type' : 'targetpatternty...
def run(self, cmd): ''' Execute the salt command given by cmd dict. cmd is a dictionary of the following form: { 'mode': 'modestring', 'fun' : 'modulefunctionstring', 'kwarg': functionkeywordargdictionary, 'tgt' : 'targetpatternstring', ...
Convenience function that returns dict of function signature(s) specified by cmd. cmd is dict of the form: { 'module' : 'modulestring', 'tgt' : 'targetpatternstring', 'tgt_type' : 'targetpatterntype', 'token': 'salttokenstring', 'username': 'u...
def signature(self, cmd): ''' Convenience function that returns dict of function signature(s) specified by cmd. cmd is dict of the form: { 'module' : 'modulestring', 'tgt' : 'targetpatternstring', 'tgt_type' : 'targetpatterntype', 'token':...
Expects everything that signature does and also a client type string. client can either be master or minion.
def _signature(self, cmd): ''' Expects everything that signature does and also a client type string. client can either be master or minion. ''' result = {} client = cmd.get('client', 'minion') if client == 'minion': cmd['fun'] = 'sys.argspec' ...
Create token with creds. Token authorizes salt access if successful authentication with the credentials in creds. creds format is as follows: { 'username': 'namestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } exam...
def create_token(self, creds): ''' Create token with creds. Token authorizes salt access if successful authentication with the credentials in creds. creds format is as follows: { 'username': 'namestring', 'password': 'passwordstring', ...
If token is valid Then returns user name associated with token Else False.
def verify_token(self, token): ''' If token is valid Then returns user name associated with token Else False. ''' try: result = self.resolver.get_token(token) except Exception as ex: raise EauthAuthenticationError( "Token validation...
Get a single salt event. If no events are available, then block for up to ``wait`` seconds. Return the event if it matches the tag (or ``tag`` is empty) Otherwise return None If wait is 0 then block forever or until next event becomes available.
def get_event(self, wait=0.25, tag='', full=False): ''' Get a single salt event. If no events are available, then block for up to ``wait`` seconds. Return the event if it matches the tag (or ``tag`` is empty) Otherwise return None If wait is 0 then block forever or until...
fires event with data and tag This only works if api is running with same user permissions as master Need to convert this to a master call with appropriate authentication
def fire_event(self, data, tag): ''' fires event with data and tag This only works if api is running with same user permissions as master Need to convert this to a master call with appropriate authentication ''' return self.event.fire_event(data, salt.utils.event.tagify(...
Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone
def get_zone(): ''' Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone ''' cmd = ['tzutil', '/g'] r...
Get current numeric timezone offset from UTC (i.e. -0700) Returns: str: Offset from UTC CLI Example: .. code-block:: bash salt '*' timezone.get_offset
def get_offset(): ''' Get current numeric timezone offset from UTC (i.e. -0700) Returns: str: Offset from UTC CLI Example: .. code-block:: bash salt '*' timezone.get_offset ''' # http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and...
Get current timezone (i.e. PST, MDT, etc) Returns: str: An abbreviated timezone code CLI Example: .. code-block:: bash salt '*' timezone.get_zonecode
def get_zonecode(): ''' Get current timezone (i.e. PST, MDT, etc) Returns: str: An abbreviated timezone code CLI Example: .. code-block:: bash salt '*' timezone.get_zonecode ''' tz_object = pytz.timezone(get_zone()) loc_time = tz_object.localize(datetime.utcnow()) ...
Sets the timezone using the tzutil. Args: timezone (str): A valid timezone Returns: bool: ``True`` if successful, otherwise ``False`` Raises: CommandExecutionError: If invalid timezone is passed CLI Example: .. code-block:: bash salt '*' timezone.set_zone 'Ameri...
def set_zone(timezone): ''' Sets the timezone using the tzutil. Args: timezone (str): A valid timezone Returns: bool: ``True`` if successful, otherwise ``False`` Raises: CommandExecutionError: If invalid timezone is passed CLI Example: .. code-block:: bash ...