text
stringlengths
81
112k
List the installed versions of python. CLI Example: .. code-block:: bash salt '*' pyenv.versions def versions(runas=None): ''' List the installed versions of python. CLI Example: .. code-block:: bash salt '*' pyenv.versions ''' ret = _pyenv_exec('versions', '--bare...
Returns or sets the currently defined default python. python=None The version to set as the default. Should match one of the versions listed by :mod:`pyenv.versions <salt.modules.pyenv.versions>`. Leave blank to return the current default. CLI Example: .. code-block:: bash ...
Execute a python command with pyenv's shims from the user or the system. CLI Example: .. code-block:: bash salt '*' pyenv.do 'gem list bundler' salt '*' pyenv.do 'gem list bundler' deploy def do(cmdline=None, runas=None): ''' Execute a python command with pyenv's shims from the user ...
Execute a python command with pyenv's shims using a specific python version. CLI Example: .. code-block:: bash salt '*' pyenv.do_with_python 2.0.0-p0 'gem list bundler' salt '*' pyenv.do_with_python 2.0.0-p0 'gem list bundler' deploy def do_with_python(python, cmdline, runas=None): ''' ...
Ensure RDS instance exists. name Name of the RDS state definition. allocated_storage The amount of storage (in gigabytes) to be initially allocated for the database instance. db_instance_class The compute and memory capacity of the Amazon RDS DB instance. engine ...
Ensure RDS replica exists. .. code-block:: yaml Ensure myrds replica RDS exists: boto_rds.create_replica: - name: myreplica - source: mydb def replica_present(name, source, db_instance_class=None, availability_zone=None, port=None, ...
Ensure DB subnet group exists. name The name for the DB subnet group. This value is stored as a lowercase string. subnet_ids A list of the EC2 Subnet IDs for the DB subnet group. Either subnet_ids or subnet_names must be provided. subnet_names A list of The EC2 Subnet name...
Ensure RDS instance is absent. name Name of the RDS instance. skip_final_snapshot Whether a final db snapshot is created before the instance is deleted. If True, no snapshot is created. If False, a snapshot is created before deleting the instance. final_db_snapshot_identif...
Ensure DB parameter group exists and update parameters. name The name for the parameter group. db_parameter_group_family The DB parameter group family name. A DB parameter group can be associated with one and only one DB parameter group family, and can be applied only to a DB i...
Convert an interval string like 1w3d6h into the number of seconds, time resolution (1 unit of the smallest specified time unit) and the modifier( '+', '-', or ''). w = week d = day h = hour m = minute s = second def _parse_interval(value): ''' Convert an interval...
WRITEME def find(path, options): ''' WRITEME ''' finder = Finder(options) for path in finder.find(path): yield path
Generate filenames in path that satisfy criteria specified in the constructor. This method is a generator and should be repeatedly called until there are no more results. def find(self, path): ''' Generate filenames in path that satisfy criteria specified in the construc...
List services belonging to this account CLI Example: salt myminion pagerduty.list_services my-pagerduty-account def list_services(profile=None, api_key=None): ''' List services belonging to this account CLI Example: salt myminion pagerduty.list_services my-pagerduty-account ''' ...
Create an event in PagerDuty. Designed for use in states. CLI Example: .. code-block:: yaml salt myminion pagerduty.create_event <service_key> <description> <details> \ profile=my-pagerduty-account The following parameters are required: service_key This key can be found by u...
Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignored if a local path is specified def add_store(name, store, s...
Execute a function through the master network interface. def master_call(self, **kwargs): ''' Execute a function through the master network interface. ''' load = kwargs load['cmd'] = self.client channel = salt.transport.client.ReqChannel.factory(self.opts, ...
Execute a runner function synchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_sync({ 'fun': 'jobs.list_jo...
Execute a function .. code-block:: python >>> opts = salt.config.master_config('/etc/salt/master') >>> runner = salt.runner.RunnerClient(opts) >>> runner.cmd('jobs.list_jobs', []) { '20131219215650131543': { 'Arguments': [300]...
Helper that allows us to turn off storing jobs for different classes that may incorporate this mixin. def store_job(self): ''' Helper that allows us to turn off storing jobs for different classes that may incorporate this mixin. ''' try: class_name = self.__c...
Execute a function from low data Low data includes: required: - fun: the name of the function to run optional: - arg: a list of args to pass to fun - kwarg: kwargs for fun - __user__: user who is running the command ...
Return a dictionary of functions and the inline documentation for each def get_docs(self, arg=None): ''' Return a dictionary of functions and the inline documentation for each ''' if arg: if '*' in arg: target_mod = arg _use_fnmatch = True ...
Execute the function in a multiprocess and return the event tag to use to watch for the return def asynchronous(self, fun, low, user='UNKNOWN', pub=None): ''' Execute the function in a multiprocess and return the event tag to use to watch for the return ''' async_pub = p...
Print all of the events with the prefix 'tag' def print_async_event(self, suffix, event): ''' Print all of the events with the prefix 'tag' ''' if not isinstance(event, dict): return # if we are "quiet", don't print if self.opts.get('quiet', False): ...
Generate a JSON file to serve as an index for short-URL lookups def write_urls_index(app, exc): ''' Generate a JSON file to serve as an index for short-URL lookups ''' inventory = os.path.join(app.builder.outdir, 'objects.inv') objects = sphinx.ext.intersphinx.fetch_inventory(app, DOCS_URL, invento...
Executes the passed command. Returns True if successful :param str cmd: The command to run :return: True if successful, otherwise False :rtype: bool :raises: Error if command fails or is not supported def execute_return_success(cmd): ''' Executes the passed command. Returns True if successfu...
Executes the passed command. Returns the standard out if successful :param str cmd: The command to run :return: The standard out of the command if successful, otherwise returns an error :rtype: str :raises: Error if command fails or is not supported def execute_return_result(cmd): ''' Ex...
Helper function to validate the enabled parameter. Boolean values are converted to "on" and "off". String values are checked to make sure they are either "on" or "off"/"yes" or "no". Integer ``0`` will return "off". All other integers will return "on" :param enabled: Enabled can be boolean True or Fals...
Wait up to ``wait`` seconds for a system parameter to be changed before deciding it hasn't changed. :param str value: The value indicating a successful change :param function check_fun: The function whose return is compared with ``value`` :param bool normalize_ret: Whether to normalize the re...
Run a launchctl command and raise an error if it fails Args: additional args are passed to launchctl sub_cmd (str): Sub command supplied to launchctl Kwargs: passed to ``cmd.run_all`` return_stdout (bool): A keyword argument. If true return the stdout of the launchctl command ...
This is a helper function for getting the available macOS services. The strategy is to look through the known system locations for launchd plist files, parse them, and use their information for populating the list of services. Services can run without a plist file present, but normally services which h...
Gets the UID or Username of the current console user. :return: The uid or username of the console user. :param bool username: Whether to return the username of the console user instead of the UID. Defaults to False :rtype: Interger of the UID, or a string of the username. Raises: Command...
This state manages software package repositories. Currently, :mod:`yum <salt.modules.yumpkg>`, :mod:`apt <salt.modules.aptpkg>`, and :mod:`zypper <salt.modules.zypper>` repositories are supported. **YUM/DNF/ZYPPER-BASED SYSTEMS** .. note:: One of ``baseurl`` or ``mirrorlist`` below is required...
This function deletes the specified repo on the system, if it exists. It is essentially a wrapper around pkg.del_repo. name The name of the package repo, as it would be referred to when running the regular package manager commands. **UBUNTU-SPECIFIC OPTIONS** ppa On Ubuntu, yo...
Read pillar data from Foreman via its API. def ext_pillar(minion_id, pillar, # pylint: disable=W0613 key=None, only=()): ''' Read pillar data from Foreman via its API. ''' url = __opts__['foreman.url'] user = __opts__['foreman.user'] password = __op...
Creates a DynamoDB table. CLI Example: .. code-block:: bash salt myminion boto_dynamodb.create_table table_name / region=us-east-1 / hash_key=id / hash_key_data_type=N / range_key=created_at / range_key_data_type=N / read_capacity_units=1 / writ...
Check to see if a table exists. CLI Example: .. code-block:: bash salt myminion boto_dynamodb.exists table_name region=us-east-1 def exists(table_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if a table exists. CLI Example: .. code-block:: bash s...
Delete a DynamoDB table. CLI Example: .. code-block:: bash salt myminion boto_dynamodb.delete table_name region=us-east-1 def delete(table_name, region=None, key=None, keyid=None, profile=None): ''' Delete a DynamoDB table. CLI Example: .. code-block:: bash salt myminion b...
Update a DynamoDB table. CLI example:: salt myminion boto_dynamodb.update table_name region=us-east-1 def update(table_name, throughput=None, global_indexes=None, region=None, key=None, keyid=None, profile=None): ''' Update a DynamoDB table. CLI example:: salt myminion bo...
Creates a single global secondary index on a DynamoDB table. CLI Example: .. code-block:: bash salt myminion boto_dynamodb.create_global_secondary_index table_name / index_name def create_global_secondary_index(table_name, global_index, region=None, key=None,...
Updates the throughput of the given global secondary indexes. CLI Example: .. code-block:: bash salt myminion boto_dynamodb.update_global_secondary_index table_name / indexes def update_global_secondary_index(table_name, global_indexes, region=None, key=None,...
Describe a DynamoDB table. CLI example:: salt myminion boto_dynamodb.describe table_name region=us-east-1 def describe(table_name, region=None, key=None, keyid=None, profile=None): ''' Describe a DynamoDB table. CLI example:: salt myminion boto_dynamodb.describe table_name region=us...
Instantiates and returns an AllIndex object given a valid index configuration CLI Example: salt myminion boto_dynamodb.extract_index index def extract_index(index_data, global_index=False): ''' Instantiates and returns an AllIndex object given a valid index configuration CLI Example: ...
Install a Perl module from CPAN CLI Example: .. code-block:: bash salt '*' cpan.install Template::Alloy def install(module): ''' Install a Perl module from CPAN CLI Example: .. code-block:: bash salt '*' cpan.install Template::Alloy ''' ret = { 'old': None,...
Attempt to remove a Perl module that was installed from CPAN. Because the ``cpan`` command doesn't actually support "uninstall"-like functionality, this function will attempt to do what it can, with what it has from CPAN. Until this function is declared stable, USE AT YOUR OWN RISK! CLI Example: ...
List installed Perl modules, and the version installed CLI Example: .. code-block:: bash salt '*' cpan.list def list_(): ''' List installed Perl modules, and the version installed CLI Example: .. code-block:: bash salt '*' cpan.list ''' ret = {} cmd = 'cpan -l'...
Show information about a specific Perl module CLI Example: .. code-block:: bash salt '*' cpan.show Template::Alloy def show(module): ''' Show information about a specific Perl module CLI Example: .. code-block:: bash salt '*' cpan.show Template::Alloy ''' ret = {} ...
Return a dict of CPAN configuration values CLI Example: .. code-block:: bash salt '*' cpan.show_config def show_config(): ''' Return a dict of CPAN configuration values CLI Example: .. code-block:: bash salt '*' cpan.show_config ''' ret = {} cmd = 'cpan -J' ...
Get a cursor and run a query. Reconnect up to `retries` times if needed. Returns: cursor, affected rows counter Raises: SaltCacheError, AttributeError, OperationalError def run_query(conn, query, retries=3): ''' Get a cursor and run a query. Reconnect up to `retries` times if needed. Return...
Create table if needed def _create_table(): ''' Create table if needed ''' # Explicitely check if the table already exists as the library logs a # warning on CREATE TABLE query = """SELECT COUNT(TABLE_NAME) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '{1}'...
Initialize connection and create table if needed def _init_client(): """Initialize connection and create table if needed """ if client is not None: return global _mysql_kwargs, _table_name _mysql_kwargs = { 'host': __opts__.get('mysql.host', '127.0.0.1'), 'user': __opts__.g...
Store a key value. def store(bank, key, data): ''' Store a key value. ''' _init_client() data = __context__['serial'].dumps(data) query = b"REPLACE INTO {0} (bank, etcd_key, data) values('{1}', '{2}', " \ b"'{3}')".format(_table_name, bank, ...
Fetch a key value. def fetch(bank, key): ''' Fetch a key value. ''' _init_client() query = "SELECT data FROM {0} WHERE bank='{1}' AND etcd_key='{2}'".format( _table_name, bank, key) cur, _ = run_query(client, query) r = cur.fetchone() cur.close() if r is None: return...
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. ''' _init_client() query = "DELETE FROM {0} WHERE bank='{1}'".format(_table_name, bank) if key is not None: query += " AND etcd_key='{...
Return an iterable object containing all entries stored in the specified bank. def ls(bank): ''' Return an iterable object containing all entries stored in the specified bank. ''' _init_client() query = "SELECT etcd_key FROM {0} WHERE bank='{1}'".format( _table_name, bank) cur, ...
Checks if the specified bank contains the specified key. def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' _init_client() query = "SELECT COUNT(data) FROM {0} WHERE bank='{1}' " \ "AND etcd_key='{2}'".format(_table_name, bank, key) cur, _ = run_qu...
Create a new database and opens it. :return: def new(self): ''' Create a new database and opens it. :return: ''' dbname = self._label() self.db_path = os.path.join(self.path, dbname) if not os.path.exists(self.db_path): os.makedirs(self.db_p...
Purge the database. :param dbid: :return: def purge(self, dbid): ''' Purge the database. :param dbid: :return: ''' db_path = os.path.join(self.path, dbid) if os.path.exists(db_path): shutil.rmtree(db_path, ignore_errors=True) ...
Flush table. :param table: :return: def flush(self, table): ''' Flush table. :param table: :return: ''' table_path = os.path.join(self.db_path, table) if os.path.exists(table_path): os.unlink(table_path)
List all the databases on the given path. :return: def list(self): ''' List all the databases on the given path. :return: ''' databases = [] for dbname in os.listdir(self.path): databases.append(dbname) return list(reversed(sorted(databases)...
Load existing tables and their descriptions. :return: def list_tables(self): ''' Load existing tables and their descriptions. :return: ''' if not self._tables: for table_name in os.listdir(self.db_path): self._tables[table_name] = self._load...
Open database from the path with the name or latest. If there are no yet databases, create a new implicitly. :return: def open(self, dbname=None): ''' Open database from the path with the name or latest. If there are no yet databases, create a new implicitly. :return: ...
Create a table from the object. NOTE: This method doesn't stores anything. :param obj: :return: def create_table_from_object(self, obj): ''' Create a table from the object. NOTE: This method doesn't stores anything. :param obj: :return: ''' ...
Store an object in the table. :param obj: An object to store :param distinct: Store object only if there is none identical of such. If at least one field is different, store it. :return: def store(self, obj, distinct=False): ''' Store an object in the ...
Update object(s) in the database. :param obj: :param matches: :param mt: :param lt: :param eq: :return: def update(self, obj, matches=None, mt=None, lt=None, eq=None): ''' Update object(s) in the database. :param obj: :param matches: ...
Delete object from the database. :param obj: :param matches: :param mt: :param lt: :param eq: :return: def delete(self, obj, matches=None, mt=None, lt=None, eq=None): ''' Delete object from the database. :param obj: :param matches: ...
Returns True if object is aligned to the criteria. :param obj: :param matches: :param mt: :param lt: :param eq: :return: Boolean def __criteria(self, obj, matches=None, mt=None, lt=None, eq=None): ''' Returns True if object is aligned to the criteria. ...
Get objects from the table. :param table_name: :param matches: Regexp. :param mt: More than. :param lt: Less than. :param eq: Equals. :return: def get(self, obj, matches=None, mt=None, lt=None, eq=None): ''' Get objects from the table. :param ta...
Send an event with the given tag and data. This is useful for sending events directly to the master from the shell with salt-run. It is also quite useful for sending events in orchestration states where the ``fire_event`` requisite isn't sufficient because it does not support sending custom data with t...
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Return cached grains of the targeted minions. tgt Target to match minion ids. .. versionchanged:: 2017.7.5,2018.3.0 The ``tgt`` argume...
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Return cached pillars of the targeted minions CLI Example: .. code-block:: bash salt-run cache.pillar def pillar(tgt=None, tgt_type='glob', **kwargs...
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Return cached mine data of the targeted minions CLI Example: .. code-block:: bash salt-run cache.mine def mine(tgt=None, tgt_type='glob', **kwargs):...
Clear the cached data/files for the targeted minions. def _clear_cache(tgt=None, tgt_type='glob', clear_pillar_flag=False, clear_grains_flag=False, clear_mine_flag=False, clear_mine_func_flag=None): ''' Clear the cached data/f...
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Clear the cached pillar, grains, and mine data of the targeted minions CLI Example: .. code-block:: bash salt-run cache.clear_all def clear_all(tgt=...
.. versionadded:: 2015.8.2 Remove the update locks for Salt components (gitfs, git_pillar, winrepo) which use gitfs backend code from salt.utils.gitfs. .. note:: Running :py:func:`cache.clear_all <salt.runners.cache.clear_all>` will not include this function as it does for pillar, grains, ...
Return cloud cache data for target. .. note:: Only works with glob matching tgt Glob Target to match minion ids provider Cloud Provider CLI Example: .. code-block:: bash salt-run cache.cloud 'salt*' salt-run cache.cloud glance.example.org provider=openstack def clo...
Lists entries stored in the specified bank. CLI Example: .. code-block:: bash salt-run cache.store mycache mykey 'The time has come the walrus said' def store(bank, key, data, cachedir=None): ''' Lists entries stored in the specified bank. CLI Example: .. code-block:: bash ...
Lists entries stored in the specified bank. CLI Example: .. code-block:: bash salt-run cache.list cloud/active/ec2/myec2 cachedir=/var/cache/salt/ def list_(bank, cachedir=None): ''' Lists entries stored in the specified bank. CLI Example: .. code-block:: bash salt-run cac...
Fetch data from a salt.cache bank. CLI Example: .. code-block:: bash salt-run cache.fetch cloud/active/ec2/myec2 myminion cachedir=/var/cache/salt/ def fetch(bank, key, cachedir=None): ''' Fetch data from a salt.cache bank. CLI Example: .. code-block:: bash salt-run cache....
Return an postgres cursor def _conn(commit=False): ''' Return an postgres cursor ''' defaults = {'host': 'localhost', 'user': 'salt', 'password': 'salt', 'dbname': 'salt', 'port': 5432} conn_kwargs = {} for key, value in defaults....
Add an item or items to a queue def insert(queue, items): ''' Add an item or items to a queue ''' handle_queue_creation(queue) with _conn(commit=True) as cur: if isinstance(items, dict): items = salt.utils.json.dumps(items) cmd = str('''INSERT INTO {0}(data) VALUES(...
Delete an item or items from a queue def delete(queue, items): ''' Delete an item or items from a queue ''' with _conn(commit=True) as cur: if isinstance(items, dict): cmd = str("""DELETE FROM {0} WHERE data = '{1}'""").format( # future lint: disable=blacklisted-function ...
Pop one or more or all items from the queue return them. def pop(queue, quantity=1, is_runner=False): ''' Pop one or more or all items from the queue return them. ''' cmd = 'SELECT id, data FROM {0}'.format(queue) if quantity != 'all': try: quantity = int(quantity) excep...
Daemonize a process def daemonize(redirect_out=True): ''' Daemonize a process ''' # Avoid circular import import salt.utils.crypt try: pid = os.fork() if pid > 0: # exit first parent salt.utils.crypt.reinit_crypto() os._exit(salt.defaults.exit...
Daemonize a module function process if multiprocessing is True and the process is not being called by salt-call def daemonize_if(opts): ''' Daemonize a module function process if multiprocessing is True and the process is not being called by salt-call ''' if 'salt-call' in sys.argv[0]: ...
Notify systemd that this process has started def notify_systemd(): ''' Notify systemd that this process has started ''' try: import systemd.daemon except ImportError: if salt.utils.path.which('systemd-notify') \ and systemd_notify_call('--booted'): # Noti...
Save the pidfile def set_pidfile(pidfile, user): ''' Save the pidfile ''' pdir = os.path.dirname(pidfile) if not os.path.isdir(pdir) and pdir: os.makedirs(pdir) try: with salt.utils.files.fopen(pidfile, 'w+') as ofile: ofile.write(str(os.getpid())) # future lint: di...
Return the pid from a pidfile as an integer def get_pidfile(pidfile): ''' Return the pid from a pidfile as an integer ''' try: with salt.utils.files.fopen(pidfile) as pdf: pid = pdf.read().strip() return int(pid) except (OSError, IOError, TypeError, ValueError): ...
Generic method for cleaning up multiprocessing procs def clean_proc(proc, wait_for_kill=10): ''' Generic method for cleaning up multiprocessing procs ''' # NoneType and other fun stuff need not apply if not proc: return try: waited = 0 while proc.is_alive(): ...
Use OS facilities to determine if a process is running def os_is_running(pid): ''' Use OS facilities to determine if a process is running ''' if isinstance(pid, six.string_types): pid = int(pid) if HAS_PSUTIL: return psutil.pid_exists(pid) else: try: os.kill(...
Create a processes and args + kwargs This will deterimine if it is a Process class, otherwise it assumes it is a function def add_process(self, tgt, args=None, kwargs=None, name=None): ''' Create a processes and args + kwargs This will deterimine if it is a Process class, otherw...
Create new process (assuming this one is dead), then remove the old one def restart_process(self, pid): ''' Create new process (assuming this one is dead), then remove the old one ''' if self._restart_processes is False: return log.info( 'Process %s (%s) ...
Load and start all available api modules def run(self, asynchronous=False): ''' Load and start all available api modules ''' log.debug('Process Manager starting!') appendproctitle(self.name) # make sure to kill the subprocesses if the parent is killed if signal....
Check the children once def check_children(self): ''' Check the children once ''' if self._restart_processes is True: for pid, mapping in six.iteritems(self._process_map): if not mapping['Process'].is_alive(): log.trace('Process restart of...
Kill all of the children def kill_children(self, *args, **kwargs): ''' Kill all of the children ''' # first lets reset signal handlers to default one to prevent running this twice signal.signal(signal.SIGTERM, signal.SIG_IGN) signal.signal(signal.SIGINT, signal.SIG_IGN) ...
Make a web call to VictorOps def _query(action=None, routing_key=None, args=None, method='GET', header_dict=None, data=None): ''' Make a web call to VictorOps ''' api_key = __salt__['config.get']('victorops.api_key') or \ __salt__['config.g...
Create an event in VictorOps. Designed for use in states. The following parameters are required: :param message_type: One of the following values: INFO, WARNING, ACKNOWLEDGEMENT, CRITICAL, RECOVERY. The following parameters are optional: :param routing_key: The key for where m...
Ensure the telemetry alert exists. name An optional description of the alarm (not currently supported by telemetry API) deployment_id Specifies the ID of the root deployment resource (replica set cluster or sharded cluster) to which this alert definition is attached metric_name ...
Ensure the telemetry alert config is deleted name An optional description of the alarms (not currently supported by telemetry API) deployment_id Specifies the ID of the root deployment resource (replica set cluster or sharded cluster) to which this alert definition is attached met...
List the installed packages. :return: A list of installed packages :rtype: list CLI Example: .. code-block:: bash salt '*' pkgutil.list def list_(): ''' List the installed packages. :return: A list of installed packages :rtype: list CLI Example: .. code-block:: ba...
Internal function to install a package from the given path def _install_from_path(path): ''' Internal function to install a package from the given path ''' if not os.path.exists(path): msg = 'File not found: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'installer -pkg "{0...