text
stringlengths
81
112k
Start a node CLI Examples: .. code-block:: bash salt-cloud -a start myinstance def start(name, call=None): ''' Start a node CLI Examples: .. code-block:: bash salt-cloud -a start myinstance ''' if call != 'action': raise SaltCloudSystemExit( 'Th...
Stop a node CLI Examples: .. code-block:: bash salt-cloud -a stop myinstance salt-cloud -a stop myinstance force=True def stop(name, force=False, call=None): ''' Stop a node CLI Examples: .. code-block:: bash salt-cloud -a stop myinstance salt-cloud -a stop...
Reboot a node CLI Examples: .. code-block:: bash salt-cloud -a reboot myinstance def reboot(name, call=None): ''' Reboot a node CLI Examples: .. code-block:: bash salt-cloud -a reboot myinstance ''' if call != 'action': raise SaltCloudSystemExit( ...
Convenience function to make the rest api call for node creation. def create_node(kwargs): ''' Convenience function to make the rest api call for node creation. ''' if not isinstance(kwargs, dict): kwargs = {} # Required parameters params = { 'Action': 'CreateInstance', ...
Create a single VM from a data dict def create(vm_): ''' Create a single VM from a data dict ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, ...
Generate aliyun request signature def _compute_signature(parameters, access_key_secret): ''' Generate aliyun request signature ''' def percent_encode(line): if not isinstance(line, six.string_types): return line s = line if sys.stdin.encoding is None: s...
Make a web call to aliyun ECS REST API def query(params=None): ''' Make a web call to aliyun ECS REST API ''' path = 'https://ecs-cn-hangzhou.aliyuncs.com' access_key_id = config.get_cloud_config_value( 'id', get_configured_provider(), __opts__, search_global=False ) access_key_sec...
Show the disk details of the instance CLI Examples: .. code-block:: bash salt-cloud -a show_disk aliyun myinstance def show_disk(name, call=None): ''' Show the disk details of the instance CLI Examples: .. code-block:: bash salt-cloud -a show_disk aliyun myinstance '''...
Get monitor data of the instance. If instance name is missing, will show all the instance monitor data on the region. CLI Examples: .. code-block:: bash salt-cloud -f list_monitor_data aliyun salt-cloud -f list_monitor_data aliyun name=AY14051311071990225bd def list_monitor_data(kwargs=N...
Show the details from aliyun image def show_image(kwargs, call=None): ''' Show the details from aliyun image ''' if call != 'function': raise SaltCloudSystemExit( 'The show_images function must be called with ' '-f or --function' ) if not isinstance(kwargs, ...
Destroy a node. CLI Example: .. code-block:: bash salt-cloud -a destroy myinstance salt-cloud -d myinstance def destroy(name, call=None): ''' Destroy a node. CLI Example: .. code-block:: bash salt-cloud -a destroy myinstance salt-cloud -d myinstance '''...
Create a temporary adminfile based on the keyword arguments passed to pkg.install. def _write_adminfile(kwargs): ''' Create a temporary adminfile based on the keyword arguments passed to pkg.install. ''' # Set the adminfile default variables email = kwargs.get('email', '') instance = kw...
List the packages currently installed as a dict: .. code-block:: python {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict: .. code-bl...
Install the passed package. Can install packages from the following sources: * Locally (package already exists on the minion * HTTP/HTTPS server * FTP server * Salt master Returns a dict containing the new package names and versions: .. code-block:: python {'<package>': {'old': '...
Remove packages with pkgrm name The name of the package to be deleted By default salt automatically provides an adminfile, to automate package removal, with these options set:: email= instance=quit partial=nocheck runlevel=nocheck idepend=nocheck rd...
Ensure trail exists. name The name of the state definition Name Name of the trail. S3BucketName Specifies the name of the Amazon S3 bucket designated for publishing log files. S3KeyPrefix Specifies the Amazon S3 key prefix that comes after the name of the ...
Ensure trail with passed properties is absent. name The name of the state definition. Name Name of the trail. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a...
Yield transport, opts for all master configured transports def iter_transport_opts(opts): ''' Yield transport, opts for all master configured transports ''' transports = set() for transport, opts_overrides in six.iteritems(opts.get('transport_opts', {})): t_opts = dict(opts) t_opts...
Only succeed if the value in the given register location is greater than the given value USAGE: .. code-block:: yaml foo: check.gt: - value: 42 run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: ...
Only succeed if the value in the given register location is greater or equal than the given value USAGE: .. code-block:: yaml foo: check.gte: - value: 42 run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: ...
Only succeed if the value in the given register location is less than the given value USAGE: .. code-block:: yaml foo: check.lt: - value: 42 run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: ...
Only succeed if the value in the given register location is less than or equal the given value USAGE: .. code-block:: yaml foo: check.lte: - value: 42 run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: ...
Only succeed if the value in the given register location is equal to the given value USAGE: .. code-block:: yaml foo: check.eq: - value: 42 run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: ...
Only succeed if the value in the given register location is not equal to the given value USAGE: .. code-block:: yaml foo: check.ne: - value: 42 run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: ...
Only succeed if the value in the given register location contains the given value USAGE: .. code-block:: yaml foo: check.contains: - value: itni run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: ...
Chekcs for a specific event match and returns result True if the match happens USAGE: .. code-block:: yaml salt/foo/*/bar: check.event run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: - check: salt/foo...
Only succeed if length of the given register location is greater than the given value. USAGE: .. code-block:: yaml foo: check.len_gt: - value: 42 run_remote_ex: local.cmd: - tgt: '*' - func: test.ping - require: ...
Configures users on network devices. :param users: Dictionary formatted as the output of the function config() :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit ...
Convert the virtualbox config file values for clone_mode into the integers the API requires def map_clonemode(vm_info): """ Convert the virtualbox config file values for clone_mode into the integers the API requires """ mode_map = { 'state': 0, 'child': 1, 'all': 2 } if not...
Creates a virtual machine from the given VM information This is what is used to request a virtual machine to be created by the cloud provider, wait for it to become available, and then (optionally) log in and install Salt on it. Events fired: This function fires the event ``salt/cloud/vm_name/cre...
All information available about all nodes should be returned in this function. The fields in the list_nodes() function should also be returned, even if they would not normally be provided by the cloud provider. This is because some functions both within Salt and 3rd party will break if an expected field is...
This function returns a list of nodes available on this cloud provider, using the following fields: id (str) image (str) size (str) state (str) private_ips (list) public_ips (list) No other fields should be returned in this function, and all of these fields should be returned, even if empt...
This function irreversibly destroys a virtual machine on the cloud provider. Before doing so, it should fire an event on the Salt event bus. The tag for this event is `salt/cloud/<vm name>/destroying`. Once the virtual machine has been destroyed, another event is fired. The tag for that event is `salt/...
Start a machine. @param name: Machine to start @type name: str @param call: Must be "action" @type call: str def start(name, call=None): ''' Start a machine. @param name: Machine to start @type name: str @param call: Must be "action" @type call: str ''' if call != 'actio...
Stop a running machine. @param name: Machine to stop @type name: str @param call: Must be "action" @type call: str def stop(name, call=None): """ Stop a running machine. @param name: Machine to stop @type name: str @param call: Must be "action" @type call: str """ if cal...
Show the details of an image def show_image(kwargs, call=None): """ Show the details of an image """ if call != 'function': raise SaltCloudSystemExit( 'The show_image action must be called with -f or --function.' ) name = kwargs['image'] log.info("Showing image %s",...
Verify that a device is mapped name The name under which the device is to be mapped device The device name, typically the device node, such as ``/dev/sdb1`` or ``UUID=066e0200-2867-4ebe-b9e6-f30026ca2314``. keyfile Either ``None`` if the password is to be entered manually ...
Ensure that a device is unmapped name The name to ensure is not mapped config Set an alternative location for the crypttab, if the map is persistent, Default is ``/etc/crypttab`` persist Set if the map should be removed from the crypttab. Default is ``True`` immediate...
Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific m...
Returns the compiled pillar either of a specific minion or just the global available pillars. This function assumes that no minion has the id ``*``. Function also accepts pillarenv as attribute in order to limit to a specific pillar branch of git CLI Example: shows minion specific pillar: .. ...
Install RVM system-wide runas The user under which to run the rvm installer script. If not specified, then it be run as the user under which Salt is running. CLI Example: .. code-block:: bash salt '*' rvm.install def install(runas=None): ''' Install RVM system-wide ...
Install a ruby implementation. ruby The version of ruby to install runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. env Environment to set for the install command. Useful for exporting compilation ...
Reinstall a ruby implementation ruby The version of ruby to reinstall runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. CLI Example: .. code-block:: bash salt '*' rvm.reinstall_ruby 1.9.3-p385 def ...
List all rvm-installed rubies runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. CLI Example: .. code-block:: bash salt '*' rvm.list def list_(runas=None): ''' List all rvm-installed rubies runas ...
Install RVM wrapper scripts ruby_string Ruby/gemset to install wrappers for wrapper_prefix What to prepend to the name of the generated wrapper binaries runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. ...
List all gemsets for the given ruby. ruby : default The ruby version for which to list the gemsets runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. CLI Example: .. code-block:: bash salt '*' rvm.ge...
List all gemsets for all installed rubies. Note that you must have set a default ruby before this can work. runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. CLI Example: .. code-block:: bash salt '*' rvm.g...
Execute a command in an RVM controlled environment. ruby Which ruby to use command The rvm command to execute runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. cwd The directory from which to...
Read a file on the file system (relative to salt's base project dir) :returns: A file-like object. :raises IOError: If the file cannot be found or read. def parse_file(self, fpath): ''' Read a file on the file system (relative to salt's base project dir) :returns: A file-like ...
Parse a string line-by-line delineating comments and code :returns: An tuple of boolean/list-of-string pairs. True designates a comment; False designates code. def parse_lit(self, lines): ''' Parse a string line-by-line delineating comments and code :returns: An tuple of b...
Given a typical Salt SLS path (e.g.: apache.vhosts.standard), find the file on the file system and parse it def parse_file(self, sls_path): ''' Given a typical Salt SLS path (e.g.: apache.vhosts.standard), find the file on the file system and parse it ''' config = self.s...
Return the minions found by looking via pillar def mmatch(expr, delimiter, greedy, opts=None): ''' Return the minions found by looking via pillar ''' if not opts: opts = __opts__ ckminions = salt.utils.minions.CkMinions(opts) return ckminions._check_compound_minions(expr, delimiter, gr...
Access/write a SysFS attribute. If the attribute is a symlink, it's destination is returned :return: value or bool CLI example: .. code-block:: bash salt '*' sysfs.attr block/sda/queue/logical_block_size def attr(key, value=None): ''' Access/write a SysFS attribute. If the attri...
Write a SysFS attribute/action CLI example: .. code-block:: bash salt '*' sysfs.write devices/system/cpu/cpu0/cpufreq/scaling_governor 'performance' def write(key, value): ''' Write a SysFS attribute/action CLI example: .. code-block:: bash salt '*' sysfs.write devices/sys...
Read from SysFS :param key: file or path in SysFS; if key is a list then root will be prefixed on each key :return: the full (tree of) SysFS attributes under key CLI example: .. code-block:: bash salt '*' sysfs.read class/net/em1/statistics def read(key, root=''): ''' Read from Sys...
Return the basename of a SysFS key path :param key: the location to resolve within SysFS :param full: full path instead of basename :return: fullpath or basename of path CLI example: .. code-block:: bash salt '*' sysfs.read class/ttyS0 def target(key, full=True): ''' Return the...
Generate a dictionary with all available interfaces relative to root. Symlinks are not followed. CLI example: .. code-block:: bash salt '*' sysfs.interfaces block/bcache0/bcache Output example: .. code-block:: json { "r": [ "state", "partial_str...
Return a Librato connection object. def _get_librato(ret=None): ''' Return a Librato connection object. ''' _options = _get_options(ret) conn = librato.connect( _options.get('email'), _options.get('api_token'), sanitizer=librato.sanitize_metric_name, hostname=_optio...
Parse the return data and return metrics to Librato. def returner(ret): ''' Parse the return data and return metrics to Librato. ''' librato_conn = _get_librato(ret) q = librato_conn.new_queue() if ret['fun'] == 'state.highstate': log.debug('Found returned Highstate data.') # ...
Returns: tuple whose first element is a bool indicating success or failure and the second element is either a ret dict for salt or an object def _common(ret, name, service_name, kwargs): ''' Returns: tuple whose first element is a bool indicating success or failure and the second elem...
Ensure an endpoint exists and is up-to-date name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint enabled Boolean to control if endpoint is enabled def present(name, service_name, auth=N...
Ensure an endpoint does not exists name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint def absent(name, service_name, auth=None, **kwargs): ''' Ensure an endpoint does not exists name ...
Return the bgp runner options. def _get_bgp_runner_opts(): ''' Return the bgp runner options. ''' runner_opts = __opts__.get('runners', {}).get('bgp', {}) return { 'tgt': runner_opts.get('tgt', _DEFAULT_TARGET), 'tgt_type': runner_opts.get('tgt_type', _DEFAULT_EXPR_FORM), 'd...
Compare two dictionaries and return a boolean value if their values match. def _compare_match(dict1, dict2): ''' Compare two dictionaries and return a boolean value if their values match. ''' for karg, warg in six.iteritems(dict1): if karg in dict2 and dict2[karg] != warg: return Fa...
Display or return the rows. def _display_runner(rows, labels, title, display=_DEFAULT_DISPLAY, outputter=_DEFAULT_OUTPUTTER): ''' Display or return the rows. ''' if display: if outputter == 'table': ret ...
Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function. Arguments: asns A list of AS numbers to search for. The runner will return only the neighbors of these AS numbers. device Filter by device name (minion ID). ip Search BGP neighbor using t...
Return a mongodb connection object def _get_conn(ret): ''' Return a mongodb connection object ''' _options = _get_options(ret) host = _options.get('host') port = _options.get('port') uri = _options.get('uri') db_ = _options.get('db') user = _options.get('user') password = _opti...
Return data to a mongodb server def returner(ret): ''' Return data to a mongodb server ''' conn, mdb = _get_conn(ret) if isinstance(ret['return'], dict): back = _remove_dots(ret['return']) else: back = ret['return'] if isinstance(ret, dict): full_ret = _remove_dots...
mongodb doesn't allow '.' in keys, but does allow unicode equivs. Apparently the docs suggest using escaped unicode full-width encodings. *sigh* \\ --> \\\\ $ --> \\\\u0024 . --> \\\\u002e Personally, I prefer URL encodings, \\ --> %5c ...
Save the load for a given job id def save_load(jid, load, minions=None): ''' Save the load for a given job id ''' conn, mdb = _get_conn(ret=None) to_save = _safe_copy(load) if PYMONGO_VERSION > _LooseVersion('2.3'): #using .copy() to ensure original data for load is unchanged m...
Return the load associated with a given job id def get_load(jid): ''' Return the load associated with a given job id ''' conn, mdb = _get_conn(ret=None) return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
Return a list of minions def get_minions(): ''' Return a list of minions ''' conn, mdb = _get_conn(ret=None) ret = [] name = mdb.saltReturns.distinct('minion') ret.append(name) return ret
Return a list of job ids def get_jids(): ''' Return a list of job ids ''' conn, mdb = _get_conn(ret=None) map = "function() { emit(this.jid, this); }" reduce = "function (key, values) { return values[0]; }" result = mdb.jobs.inline_map_reduce(map, reduce) ret = {} for r in result: ...
Return events to Mongodb server def event_return(events): ''' Return events to Mongodb server ''' conn, mdb = _get_conn(ret=None) if isinstance(events, list): events = events[0] if isinstance(events, dict): log.debug(events) if PYMONGO_VERSION > _LooseVersion('2.3'): ...
Create a list of file ref objects to reconcile def lowstate_file_refs(chunks): ''' Create a list of file ref objects to reconcile ''' refs = {} for chunk in chunks: saltenv = 'base' crefs = [] for state in chunk: if state == '__env__': saltenv = c...
Pull salt file references out of the states def salt_refs(data): ''' Pull salt file references out of the states ''' proto = 'salt://' ret = [] if isinstance(data, six.string_types): if data.startswith(proto): return [data] if isinstance(data, list): for comp in ...
Generate the module arguments for the shim data def mod_data(fsclient): ''' Generate the module arguments for the shim data ''' # TODO, change out for a fileserver backend sync_refs = [ 'modules', 'states', 'grains', 'renderers', 'returner...
Returns the version of the installed ssh command def ssh_version(): ''' Returns the version of the installed ssh command ''' # This function needs more granular checks and to be validated against # older versions of ssh ret = subprocess.Popen( ['ssh', '-V'], stdout=subpr...
Take a list of args, and convert any dicts inside the list to keyword args in the form of `key=value`, ready to be passed to salt-ssh def _convert_args(args): ''' Take a list of args, and convert any dicts inside the list to keyword args in the form of `key=value`, ready to be passed to salt-ssh ''...
Read roster filename as a key to the data. :return: def _get_roster(self): ''' Read roster filename as a key to the data. :return: ''' roster_file = salt.roster.get_roster_file(self.opts) if roster_file not in self.__parsed_rosters: roster_data = comp...
Figures out if the target is a reachable host without wildcards, expands if any. :return: def _expand_target(self): ''' Figures out if the target is a reachable host without wildcards, expands if any. :return: ''' # TODO: Support -L target = self.opts['tgt'] ...
Update default flat roster with the passed in information. :return: def _update_roster(self): ''' Update default flat roster with the passed in information. :return: ''' roster_file = self._get_roster() if os.access(roster_file, os.W_OK): if self.__pa...
Uptade targets in case hostname was directly passed without the roster. :return: def _update_targets(self): ''' Uptade targets in case hostname was directly passed without the roster. :return: ''' hostname = self.opts.get('tgt', '') if '@' in hostname: ...
Return the key string for the SSH public key def get_pubkey(self): ''' Return the key string for the SSH public key ''' if '__master_opts__' in self.opts and \ self.opts['__master_opts__'].get('ssh_use_home_key') and \ os.path.isfile(os.path.expanduser('~...
Deploy the SSH key if the minions don't auth def key_deploy(self, host, ret): ''' Deploy the SSH key if the minions don't auth ''' if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'): target = self.targets[host] if target.get('passwd', False) or...
The ssh-copy-id routine def _key_deploy_run(self, host, target, re_run=True): ''' The ssh-copy-id routine ''' argv = [ 'ssh.set_auth_key', target.get('user', 'root'), self.get_pubkey(), ] single = Single( self.opts, ...
Run the routine in a "Thread", put a dict on the queue def handle_routine(self, que, opts, host, target, mine=False): ''' Run the routine in a "Thread", put a dict on the queue ''' opts = copy.deepcopy(opts) single = Single( opts, opts['argv'], ...
Spin up the needed threads or processes and execute the subsequent routines def handle_ssh(self, mine=False): ''' Spin up the needed threads or processes and execute the subsequent routines ''' que = multiprocessing.Queue() running = {} target_iter = self...
Execute and yield returns as they come in, do not print to the display mine The Single objects will use mine_functions defined in the roster, pillar, or master config (they will be checked in that order) and will modify the argv with the arguments from mine_functions def ru...
Cache the job information def cache_job(self, jid, id_, ret, fun): ''' Cache the job information ''' self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid, 'id': id_, ...
Execute the overall routine, print results via outputters def run(self, jid=None): ''' Execute the overall routine, print results via outputters ''' if self.opts.get('list_hosts'): self._get_roster() ret = {} for roster_file in self.__parsed_rosters: ...
Return the function name and the arg list def __arg_comps(self): ''' Return the function name and the arg list ''' fun = self.argv[0] if self.argv else '' parsed = salt.utils.args.parse_input( self.argv[1:], condition=False, no_parse=self.opts...
Properly escape argument to protect special characters from shell interpretation. This avoids having to do tricky argument quoting. Effectively just escape all characters in the argument that are not alphanumeric! def _escape_arg(self, arg): ''' Properly escape argument to pro...
Deploy salt-thin def deploy(self): ''' Deploy salt-thin ''' self.shell.send( self.thin, os.path.join(self.thin_dir, 'salt-thin.tgz'), ) self.deploy_ext() return True
Deploy the ext_mods tarball def deploy_ext(self): ''' Deploy the ext_mods tarball ''' if self.mods.get('file'): self.shell.send( self.mods['file'], os.path.join(self.thin_dir, 'salt-ext_mods.tgz'), ) return True
Execute the routine, the routine can be either: 1. Execute a raw shell command 2. Execute a wrapper func 3. Execute a remote Salt command If a (re)deploy is needed, then retry the operation after a deploy attempt Returns tuple of (stdout, stderr, retcode) def run(self,...
Execute a wrapper function Returns tuple of (json_data, '') def run_wfunc(self): ''' Execute a wrapper function Returns tuple of (json_data, '') ''' # Ensure that opts/grains are up to date # Execute routine data_cache = False data = None ...
Prepare the command string def _cmd_str(self): ''' Prepare the command string ''' sudo = 'sudo' if self.target['sudo'] else '' sudo_user = self.target['sudo_user'] if '_caller_cachedir' in self.opts: cachedir = self.opts['_caller_cachedir'] else: ...
Run a shim command. If tty is enabled, we must scp the shim to the target system and execute it there def shim_cmd(self, cmd_str, extension='py'): ''' Run a shim command. If tty is enabled, we must scp the shim to the target system and execute it there ''' ...
Prepare the pre-check command to send to the subsystem 1. execute SHIM + command 2. check if SHIM returns a master request or if it completed 3. handle any master request 4. re-execute SHIM + command 5. split SHIM results from command results 6. return command results d...