repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/runners/fileserver.py
|
dir_list
|
python
|
def dir_list(saltenv='base', backend=None):
'''
Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.dir_list(load=load)
|
Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L242-L285
| null |
# -*- coding: utf-8 -*-
'''
Directly manage the Salt fileserver plugins
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.fileserver
def envs(backend=None, sources=False):
'''
Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.envs
salt-run fileserver.envs backend=roots,git
salt-run fileserver.envs git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
return sorted(fileserver.envs(back=backend, sources=sources))
def clear_file_list_cache(saltenv=None, backend=None):
'''
.. versionadded:: 2016.11.0
The Salt fileserver caches the files/directories/symlinks for each
fileserver backend and environment as they are requested. This is done to
help the fileserver scale better. Without this caching, when
hundreds/thousands of minions simultaneously ask the master what files are
available, this would cause the master's CPU load to spike as it obtains
the same information separately for each minion.
saltenv
By default, this runner will clear the file list caches for all
environments. This argument allows for a list of environments to be
passed, to clear more selectively. This list can be passed either as a
comma-separated string, or a Python list.
backend
Similar to the ``saltenv`` parameter, this argument will restrict the
cache clearing to specific fileserver backends (the default behavior is
to clear from all enabled fileserver backends). This list can be passed
either as a comma-separated string, or a Python list.
.. note:
The maximum age for the cached file lists (i.e. the age at which the
cache will be disregarded and rebuilt) is defined by the
:conf_master:`fileserver_list_cache_time` configuration parameter.
Since the ability to clear these caches is often required by users writing
custom runners which add/remove files, this runner can easily be called
from within a custom runner using any of the following examples:
.. code-block:: python
# Clear all file list caches
__salt__['fileserver.clear_file_list_cache']()
# Clear just the 'base' saltenv file list caches
__salt__['fileserver.clear_file_list_cache'](saltenv='base')
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
__salt__['fileserver.clear_file_list_cache'](saltenv='base', backend='roots')
# Clear all file list caches from the 'roots' fileserver backend
__salt__['fileserver.clear_file_list_cache'](backend='roots')
.. note::
In runners, the ``__salt__`` dictionary will likely be renamed to
``__runner__`` in a future Salt release to distinguish runner functions
from remote execution functions. See `this GitHub issue`_ for
discussion/updates on this.
.. _`this GitHub issue`: https://github.com/saltstack/salt/issues/34958
If using Salt's Python API (not a runner), the following examples are
equivalent to the ones above:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
opts['fun'] = 'fileserver.clear_file_list_cache'
# Clear all file list_caches
opts['arg'] = [] # No arguments
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches
opts['arg'] = ['base', None]
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
opts['arg'] = ['base', 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear all file list caches from the 'roots' fileserver backend
opts['arg'] = [None, 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
This function will return a dictionary showing a list of environments which
were cleared for each backend. An empty return dictionary means that no
changes were made.
CLI Examples:
.. code-block:: bash
# Clear all file list caches
salt-run fileserver.clear_file_list_cache
# Clear just the 'base' saltenv file list caches
salt-run fileserver.clear_file_list_cache saltenv=base
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
salt-run fileserver.clear_file_list_cache saltenv=base backend=roots
# Clear all file list caches from the 'roots' fileserver backend
salt-run fileserver.clear_file_list_cache backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.clear_file_list_cache(load=load)
def file_list(saltenv='base', backend=None):
'''
Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what files are available to minions.
When in doubt, use :py:func:`cp.list_master
<salt.modules.cp.list_master>` to see what files the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Examples:
.. code-block:: bash
salt-run fileserver.file_list
salt-run fileserver.file_list saltenv=prod
salt-run fileserver.file_list saltenv=dev backend=git
salt-run fileserver.file_list base hg,roots
salt-run fileserver.file_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list(load=load)
def symlink_list(saltenv='base', backend=None):
'''
Return a list of symlinked files and dirs
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what symlinks are available to minions.
When in doubt, use :py:func:`cp.list_master_symlinks
<salt.modules.cp.list_master_symlinks>` to see what symlinks the minion
can see, and always remember to restart the salt-master daemon when
updating the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.symlink_list
salt-run fileserver.symlink_list saltenv=prod
salt-run fileserver.symlink_list saltenv=dev backend=git
salt-run fileserver.symlink_list base hg,roots
salt-run fileserver.symlink_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.symlink_list(load=load)
def empty_dir_list(saltenv='base', backend=None):
'''
.. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list_emptydirs(load=load)
def update(backend=None):
'''
Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
fileserver.update(back=backend)
return True
def clear_cache(backend=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_cache(back=backend)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No cache was cleared'
return ret
def clear_lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_lock(back=backend, remote=remote)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were removed'
return ret
def lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
locked, errors = fileserver.lock(back=backend, remote=remote)
ret = {}
if locked:
ret['locked'] = locked
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were set'
return ret
|
saltstack/salt
|
salt/runners/fileserver.py
|
empty_dir_list
|
python
|
def empty_dir_list(saltenv='base', backend=None):
'''
.. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list_emptydirs(load=load)
|
.. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L288-L322
| null |
# -*- coding: utf-8 -*-
'''
Directly manage the Salt fileserver plugins
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.fileserver
def envs(backend=None, sources=False):
'''
Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.envs
salt-run fileserver.envs backend=roots,git
salt-run fileserver.envs git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
return sorted(fileserver.envs(back=backend, sources=sources))
def clear_file_list_cache(saltenv=None, backend=None):
'''
.. versionadded:: 2016.11.0
The Salt fileserver caches the files/directories/symlinks for each
fileserver backend and environment as they are requested. This is done to
help the fileserver scale better. Without this caching, when
hundreds/thousands of minions simultaneously ask the master what files are
available, this would cause the master's CPU load to spike as it obtains
the same information separately for each minion.
saltenv
By default, this runner will clear the file list caches for all
environments. This argument allows for a list of environments to be
passed, to clear more selectively. This list can be passed either as a
comma-separated string, or a Python list.
backend
Similar to the ``saltenv`` parameter, this argument will restrict the
cache clearing to specific fileserver backends (the default behavior is
to clear from all enabled fileserver backends). This list can be passed
either as a comma-separated string, or a Python list.
.. note:
The maximum age for the cached file lists (i.e. the age at which the
cache will be disregarded and rebuilt) is defined by the
:conf_master:`fileserver_list_cache_time` configuration parameter.
Since the ability to clear these caches is often required by users writing
custom runners which add/remove files, this runner can easily be called
from within a custom runner using any of the following examples:
.. code-block:: python
# Clear all file list caches
__salt__['fileserver.clear_file_list_cache']()
# Clear just the 'base' saltenv file list caches
__salt__['fileserver.clear_file_list_cache'](saltenv='base')
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
__salt__['fileserver.clear_file_list_cache'](saltenv='base', backend='roots')
# Clear all file list caches from the 'roots' fileserver backend
__salt__['fileserver.clear_file_list_cache'](backend='roots')
.. note::
In runners, the ``__salt__`` dictionary will likely be renamed to
``__runner__`` in a future Salt release to distinguish runner functions
from remote execution functions. See `this GitHub issue`_ for
discussion/updates on this.
.. _`this GitHub issue`: https://github.com/saltstack/salt/issues/34958
If using Salt's Python API (not a runner), the following examples are
equivalent to the ones above:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
opts['fun'] = 'fileserver.clear_file_list_cache'
# Clear all file list_caches
opts['arg'] = [] # No arguments
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches
opts['arg'] = ['base', None]
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
opts['arg'] = ['base', 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear all file list caches from the 'roots' fileserver backend
opts['arg'] = [None, 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
This function will return a dictionary showing a list of environments which
were cleared for each backend. An empty return dictionary means that no
changes were made.
CLI Examples:
.. code-block:: bash
# Clear all file list caches
salt-run fileserver.clear_file_list_cache
# Clear just the 'base' saltenv file list caches
salt-run fileserver.clear_file_list_cache saltenv=base
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
salt-run fileserver.clear_file_list_cache saltenv=base backend=roots
# Clear all file list caches from the 'roots' fileserver backend
salt-run fileserver.clear_file_list_cache backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.clear_file_list_cache(load=load)
def file_list(saltenv='base', backend=None):
'''
Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what files are available to minions.
When in doubt, use :py:func:`cp.list_master
<salt.modules.cp.list_master>` to see what files the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Examples:
.. code-block:: bash
salt-run fileserver.file_list
salt-run fileserver.file_list saltenv=prod
salt-run fileserver.file_list saltenv=dev backend=git
salt-run fileserver.file_list base hg,roots
salt-run fileserver.file_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list(load=load)
def symlink_list(saltenv='base', backend=None):
'''
Return a list of symlinked files and dirs
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what symlinks are available to minions.
When in doubt, use :py:func:`cp.list_master_symlinks
<salt.modules.cp.list_master_symlinks>` to see what symlinks the minion
can see, and always remember to restart the salt-master daemon when
updating the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.symlink_list
salt-run fileserver.symlink_list saltenv=prod
salt-run fileserver.symlink_list saltenv=dev backend=git
salt-run fileserver.symlink_list base hg,roots
salt-run fileserver.symlink_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.symlink_list(load=load)
def dir_list(saltenv='base', backend=None):
'''
Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.dir_list(load=load)
def update(backend=None):
'''
Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
fileserver.update(back=backend)
return True
def clear_cache(backend=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_cache(back=backend)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No cache was cleared'
return ret
def clear_lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_lock(back=backend, remote=remote)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were removed'
return ret
def lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
locked, errors = fileserver.lock(back=backend, remote=remote)
ret = {}
if locked:
ret['locked'] = locked
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were set'
return ret
|
saltstack/salt
|
salt/runners/fileserver.py
|
update
|
python
|
def update(backend=None):
'''
Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
fileserver.update(back=backend)
return True
|
Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L325-L353
|
[
"def update(self, back=None):\n '''\n Update all of the enabled fileserver backends which support the update\n function, or\n '''\n back = self.backends(back)\n for fsb in back:\n fstr = '{0}.update'.format(fsb)\n if fstr in self.servers:\n log.debug('Updating %s fileserver cache', fsb)\n self.servers[fstr]()\n"
] |
# -*- coding: utf-8 -*-
'''
Directly manage the Salt fileserver plugins
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.fileserver
def envs(backend=None, sources=False):
'''
Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.envs
salt-run fileserver.envs backend=roots,git
salt-run fileserver.envs git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
return sorted(fileserver.envs(back=backend, sources=sources))
def clear_file_list_cache(saltenv=None, backend=None):
'''
.. versionadded:: 2016.11.0
The Salt fileserver caches the files/directories/symlinks for each
fileserver backend and environment as they are requested. This is done to
help the fileserver scale better. Without this caching, when
hundreds/thousands of minions simultaneously ask the master what files are
available, this would cause the master's CPU load to spike as it obtains
the same information separately for each minion.
saltenv
By default, this runner will clear the file list caches for all
environments. This argument allows for a list of environments to be
passed, to clear more selectively. This list can be passed either as a
comma-separated string, or a Python list.
backend
Similar to the ``saltenv`` parameter, this argument will restrict the
cache clearing to specific fileserver backends (the default behavior is
to clear from all enabled fileserver backends). This list can be passed
either as a comma-separated string, or a Python list.
.. note:
The maximum age for the cached file lists (i.e. the age at which the
cache will be disregarded and rebuilt) is defined by the
:conf_master:`fileserver_list_cache_time` configuration parameter.
Since the ability to clear these caches is often required by users writing
custom runners which add/remove files, this runner can easily be called
from within a custom runner using any of the following examples:
.. code-block:: python
# Clear all file list caches
__salt__['fileserver.clear_file_list_cache']()
# Clear just the 'base' saltenv file list caches
__salt__['fileserver.clear_file_list_cache'](saltenv='base')
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
__salt__['fileserver.clear_file_list_cache'](saltenv='base', backend='roots')
# Clear all file list caches from the 'roots' fileserver backend
__salt__['fileserver.clear_file_list_cache'](backend='roots')
.. note::
In runners, the ``__salt__`` dictionary will likely be renamed to
``__runner__`` in a future Salt release to distinguish runner functions
from remote execution functions. See `this GitHub issue`_ for
discussion/updates on this.
.. _`this GitHub issue`: https://github.com/saltstack/salt/issues/34958
If using Salt's Python API (not a runner), the following examples are
equivalent to the ones above:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
opts['fun'] = 'fileserver.clear_file_list_cache'
# Clear all file list_caches
opts['arg'] = [] # No arguments
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches
opts['arg'] = ['base', None]
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
opts['arg'] = ['base', 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear all file list caches from the 'roots' fileserver backend
opts['arg'] = [None, 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
This function will return a dictionary showing a list of environments which
were cleared for each backend. An empty return dictionary means that no
changes were made.
CLI Examples:
.. code-block:: bash
# Clear all file list caches
salt-run fileserver.clear_file_list_cache
# Clear just the 'base' saltenv file list caches
salt-run fileserver.clear_file_list_cache saltenv=base
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
salt-run fileserver.clear_file_list_cache saltenv=base backend=roots
# Clear all file list caches from the 'roots' fileserver backend
salt-run fileserver.clear_file_list_cache backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.clear_file_list_cache(load=load)
def file_list(saltenv='base', backend=None):
'''
Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what files are available to minions.
When in doubt, use :py:func:`cp.list_master
<salt.modules.cp.list_master>` to see what files the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Examples:
.. code-block:: bash
salt-run fileserver.file_list
salt-run fileserver.file_list saltenv=prod
salt-run fileserver.file_list saltenv=dev backend=git
salt-run fileserver.file_list base hg,roots
salt-run fileserver.file_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list(load=load)
def symlink_list(saltenv='base', backend=None):
'''
Return a list of symlinked files and dirs
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what symlinks are available to minions.
When in doubt, use :py:func:`cp.list_master_symlinks
<salt.modules.cp.list_master_symlinks>` to see what symlinks the minion
can see, and always remember to restart the salt-master daemon when
updating the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.symlink_list
salt-run fileserver.symlink_list saltenv=prod
salt-run fileserver.symlink_list saltenv=dev backend=git
salt-run fileserver.symlink_list base hg,roots
salt-run fileserver.symlink_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.symlink_list(load=load)
def dir_list(saltenv='base', backend=None):
'''
Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.dir_list(load=load)
def empty_dir_list(saltenv='base', backend=None):
'''
.. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list_emptydirs(load=load)
def clear_cache(backend=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_cache(back=backend)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No cache was cleared'
return ret
def clear_lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_lock(back=backend, remote=remote)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were removed'
return ret
def lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
locked, errors = fileserver.lock(back=backend, remote=remote)
ret = {}
if locked:
ret['locked'] = locked
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were set'
return ret
|
saltstack/salt
|
salt/runners/fileserver.py
|
clear_cache
|
python
|
def clear_cache(backend=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_cache(back=backend)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No cache was cleared'
return ret
|
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L356-L391
|
[
"def clear_cache(self, back=None):\n '''\n Clear the cache of all of the fileserver backends that support the\n clear_cache function or the named backend(s) only.\n '''\n back = self.backends(back)\n cleared = []\n errors = []\n for fsb in back:\n fstr = '{0}.clear_cache'.format(fsb)\n if fstr in self.servers:\n log.debug('Clearing %s fileserver cache', fsb)\n failed = self.servers[fstr]()\n if failed:\n errors.extend(failed)\n else:\n cleared.append(\n 'The {0} fileserver cache was successfully cleared'\n .format(fsb)\n )\n return cleared, errors\n"
] |
# -*- coding: utf-8 -*-
'''
Directly manage the Salt fileserver plugins
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.fileserver
def envs(backend=None, sources=False):
'''
Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.envs
salt-run fileserver.envs backend=roots,git
salt-run fileserver.envs git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
return sorted(fileserver.envs(back=backend, sources=sources))
def clear_file_list_cache(saltenv=None, backend=None):
'''
.. versionadded:: 2016.11.0
The Salt fileserver caches the files/directories/symlinks for each
fileserver backend and environment as they are requested. This is done to
help the fileserver scale better. Without this caching, when
hundreds/thousands of minions simultaneously ask the master what files are
available, this would cause the master's CPU load to spike as it obtains
the same information separately for each minion.
saltenv
By default, this runner will clear the file list caches for all
environments. This argument allows for a list of environments to be
passed, to clear more selectively. This list can be passed either as a
comma-separated string, or a Python list.
backend
Similar to the ``saltenv`` parameter, this argument will restrict the
cache clearing to specific fileserver backends (the default behavior is
to clear from all enabled fileserver backends). This list can be passed
either as a comma-separated string, or a Python list.
.. note:
The maximum age for the cached file lists (i.e. the age at which the
cache will be disregarded and rebuilt) is defined by the
:conf_master:`fileserver_list_cache_time` configuration parameter.
Since the ability to clear these caches is often required by users writing
custom runners which add/remove files, this runner can easily be called
from within a custom runner using any of the following examples:
.. code-block:: python
# Clear all file list caches
__salt__['fileserver.clear_file_list_cache']()
# Clear just the 'base' saltenv file list caches
__salt__['fileserver.clear_file_list_cache'](saltenv='base')
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
__salt__['fileserver.clear_file_list_cache'](saltenv='base', backend='roots')
# Clear all file list caches from the 'roots' fileserver backend
__salt__['fileserver.clear_file_list_cache'](backend='roots')
.. note::
In runners, the ``__salt__`` dictionary will likely be renamed to
``__runner__`` in a future Salt release to distinguish runner functions
from remote execution functions. See `this GitHub issue`_ for
discussion/updates on this.
.. _`this GitHub issue`: https://github.com/saltstack/salt/issues/34958
If using Salt's Python API (not a runner), the following examples are
equivalent to the ones above:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
opts['fun'] = 'fileserver.clear_file_list_cache'
# Clear all file list_caches
opts['arg'] = [] # No arguments
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches
opts['arg'] = ['base', None]
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
opts['arg'] = ['base', 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear all file list caches from the 'roots' fileserver backend
opts['arg'] = [None, 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
This function will return a dictionary showing a list of environments which
were cleared for each backend. An empty return dictionary means that no
changes were made.
CLI Examples:
.. code-block:: bash
# Clear all file list caches
salt-run fileserver.clear_file_list_cache
# Clear just the 'base' saltenv file list caches
salt-run fileserver.clear_file_list_cache saltenv=base
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
salt-run fileserver.clear_file_list_cache saltenv=base backend=roots
# Clear all file list caches from the 'roots' fileserver backend
salt-run fileserver.clear_file_list_cache backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.clear_file_list_cache(load=load)
def file_list(saltenv='base', backend=None):
'''
Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what files are available to minions.
When in doubt, use :py:func:`cp.list_master
<salt.modules.cp.list_master>` to see what files the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Examples:
.. code-block:: bash
salt-run fileserver.file_list
salt-run fileserver.file_list saltenv=prod
salt-run fileserver.file_list saltenv=dev backend=git
salt-run fileserver.file_list base hg,roots
salt-run fileserver.file_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list(load=load)
def symlink_list(saltenv='base', backend=None):
'''
Return a list of symlinked files and dirs
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what symlinks are available to minions.
When in doubt, use :py:func:`cp.list_master_symlinks
<salt.modules.cp.list_master_symlinks>` to see what symlinks the minion
can see, and always remember to restart the salt-master daemon when
updating the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.symlink_list
salt-run fileserver.symlink_list saltenv=prod
salt-run fileserver.symlink_list saltenv=dev backend=git
salt-run fileserver.symlink_list base hg,roots
salt-run fileserver.symlink_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.symlink_list(load=load)
def dir_list(saltenv='base', backend=None):
'''
Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.dir_list(load=load)
def empty_dir_list(saltenv='base', backend=None):
'''
.. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list_emptydirs(load=load)
def update(backend=None):
'''
Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
fileserver.update(back=backend)
return True
def clear_lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_lock(back=backend, remote=remote)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were removed'
return ret
def lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
locked, errors = fileserver.lock(back=backend, remote=remote)
ret = {}
if locked:
ret['locked'] = locked
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were set'
return ret
|
saltstack/salt
|
salt/runners/fileserver.py
|
clear_lock
|
python
|
def clear_lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_lock(back=backend, remote=remote)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were removed'
return ret
|
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L394-L432
|
[
"def clear_lock(self, back=None, remote=None):\n '''\n Clear the update lock for the enabled fileserver backends\n\n back\n Only clear the update lock for the specified backend(s). The\n default is to clear the lock for all enabled backends\n\n remote\n If specified, then any remotes which contain the passed string will\n have their lock cleared.\n '''\n back = self.backends(back)\n cleared = []\n errors = []\n for fsb in back:\n fstr = '{0}.clear_lock'.format(fsb)\n if fstr in self.servers:\n good, bad = clear_lock(self.servers[fstr],\n fsb,\n remote=remote)\n cleared.extend(good)\n errors.extend(bad)\n return cleared, errors\n"
] |
# -*- coding: utf-8 -*-
'''
Directly manage the Salt fileserver plugins
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.fileserver
def envs(backend=None, sources=False):
'''
Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.envs
salt-run fileserver.envs backend=roots,git
salt-run fileserver.envs git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
return sorted(fileserver.envs(back=backend, sources=sources))
def clear_file_list_cache(saltenv=None, backend=None):
'''
.. versionadded:: 2016.11.0
The Salt fileserver caches the files/directories/symlinks for each
fileserver backend and environment as they are requested. This is done to
help the fileserver scale better. Without this caching, when
hundreds/thousands of minions simultaneously ask the master what files are
available, this would cause the master's CPU load to spike as it obtains
the same information separately for each minion.
saltenv
By default, this runner will clear the file list caches for all
environments. This argument allows for a list of environments to be
passed, to clear more selectively. This list can be passed either as a
comma-separated string, or a Python list.
backend
Similar to the ``saltenv`` parameter, this argument will restrict the
cache clearing to specific fileserver backends (the default behavior is
to clear from all enabled fileserver backends). This list can be passed
either as a comma-separated string, or a Python list.
.. note:
The maximum age for the cached file lists (i.e. the age at which the
cache will be disregarded and rebuilt) is defined by the
:conf_master:`fileserver_list_cache_time` configuration parameter.
Since the ability to clear these caches is often required by users writing
custom runners which add/remove files, this runner can easily be called
from within a custom runner using any of the following examples:
.. code-block:: python
# Clear all file list caches
__salt__['fileserver.clear_file_list_cache']()
# Clear just the 'base' saltenv file list caches
__salt__['fileserver.clear_file_list_cache'](saltenv='base')
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
__salt__['fileserver.clear_file_list_cache'](saltenv='base', backend='roots')
# Clear all file list caches from the 'roots' fileserver backend
__salt__['fileserver.clear_file_list_cache'](backend='roots')
.. note::
In runners, the ``__salt__`` dictionary will likely be renamed to
``__runner__`` in a future Salt release to distinguish runner functions
from remote execution functions. See `this GitHub issue`_ for
discussion/updates on this.
.. _`this GitHub issue`: https://github.com/saltstack/salt/issues/34958
If using Salt's Python API (not a runner), the following examples are
equivalent to the ones above:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
opts['fun'] = 'fileserver.clear_file_list_cache'
# Clear all file list_caches
opts['arg'] = [] # No arguments
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches
opts['arg'] = ['base', None]
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
opts['arg'] = ['base', 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear all file list caches from the 'roots' fileserver backend
opts['arg'] = [None, 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
This function will return a dictionary showing a list of environments which
were cleared for each backend. An empty return dictionary means that no
changes were made.
CLI Examples:
.. code-block:: bash
# Clear all file list caches
salt-run fileserver.clear_file_list_cache
# Clear just the 'base' saltenv file list caches
salt-run fileserver.clear_file_list_cache saltenv=base
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
salt-run fileserver.clear_file_list_cache saltenv=base backend=roots
# Clear all file list caches from the 'roots' fileserver backend
salt-run fileserver.clear_file_list_cache backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.clear_file_list_cache(load=load)
def file_list(saltenv='base', backend=None):
'''
Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what files are available to minions.
When in doubt, use :py:func:`cp.list_master
<salt.modules.cp.list_master>` to see what files the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Examples:
.. code-block:: bash
salt-run fileserver.file_list
salt-run fileserver.file_list saltenv=prod
salt-run fileserver.file_list saltenv=dev backend=git
salt-run fileserver.file_list base hg,roots
salt-run fileserver.file_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list(load=load)
def symlink_list(saltenv='base', backend=None):
'''
Return a list of symlinked files and dirs
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what symlinks are available to minions.
When in doubt, use :py:func:`cp.list_master_symlinks
<salt.modules.cp.list_master_symlinks>` to see what symlinks the minion
can see, and always remember to restart the salt-master daemon when
updating the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.symlink_list
salt-run fileserver.symlink_list saltenv=prod
salt-run fileserver.symlink_list saltenv=dev backend=git
salt-run fileserver.symlink_list base hg,roots
salt-run fileserver.symlink_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.symlink_list(load=load)
def dir_list(saltenv='base', backend=None):
'''
Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.dir_list(load=load)
def empty_dir_list(saltenv='base', backend=None):
'''
.. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list_emptydirs(load=load)
def update(backend=None):
'''
Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
fileserver.update(back=backend)
return True
def clear_cache(backend=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_cache(back=backend)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No cache was cleared'
return ret
def lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
locked, errors = fileserver.lock(back=backend, remote=remote)
ret = {}
if locked:
ret['locked'] = locked
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were set'
return ret
|
saltstack/salt
|
salt/runners/fileserver.py
|
lock
|
python
|
def lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
locked, errors = fileserver.lock(back=backend, remote=remote)
ret = {}
if locked:
ret['locked'] = locked
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were set'
return ret
|
.. versionadded:: 2015.5.0
Set a fileserver update lock for VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`).
.. note::
This will only operate on enabled backends (those configured in
:conf_master:`fileserver_backend`).
backend
Only set the update lock for the specified backend(s).
remote
If not None, then any remotes which contain the passed string will have
their lock cleared. For example, a ``remote`` value of ``*github.com*``
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.lock
salt-run fileserver.lock backend=git,hg
salt-run fileserver.lock backend=git remote='*github.com*'
salt-run fileserver.lock remote=bitbucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/fileserver.py#L435-L474
|
[
"def lock(self, back=None, remote=None):\n '''\n ``remote`` can either be a dictionary containing repo configuration\n information, or a pattern. If the latter, then remotes for which the URL\n matches the pattern will be locked.\n '''\n back = self.backends(back)\n locked = []\n errors = []\n for fsb in back:\n fstr = '{0}.lock'.format(fsb)\n if fstr in self.servers:\n msg = 'Setting update lock for {0} remotes'.format(fsb)\n if remote:\n if not isinstance(remote, six.string_types):\n errors.append(\n 'Badly formatted remote pattern \\'{0}\\''\n .format(remote)\n )\n continue\n else:\n msg += ' matching {0}'.format(remote)\n log.debug(msg)\n good, bad = self.servers[fstr](remote=remote)\n locked.extend(good)\n errors.extend(bad)\n return locked, errors\n"
] |
# -*- coding: utf-8 -*-
'''
Directly manage the Salt fileserver plugins
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.fileserver
def envs(backend=None, sources=False):
'''
Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.envs
salt-run fileserver.envs backend=roots,git
salt-run fileserver.envs git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
return sorted(fileserver.envs(back=backend, sources=sources))
def clear_file_list_cache(saltenv=None, backend=None):
'''
.. versionadded:: 2016.11.0
The Salt fileserver caches the files/directories/symlinks for each
fileserver backend and environment as they are requested. This is done to
help the fileserver scale better. Without this caching, when
hundreds/thousands of minions simultaneously ask the master what files are
available, this would cause the master's CPU load to spike as it obtains
the same information separately for each minion.
saltenv
By default, this runner will clear the file list caches for all
environments. This argument allows for a list of environments to be
passed, to clear more selectively. This list can be passed either as a
comma-separated string, or a Python list.
backend
Similar to the ``saltenv`` parameter, this argument will restrict the
cache clearing to specific fileserver backends (the default behavior is
to clear from all enabled fileserver backends). This list can be passed
either as a comma-separated string, or a Python list.
.. note:
The maximum age for the cached file lists (i.e. the age at which the
cache will be disregarded and rebuilt) is defined by the
:conf_master:`fileserver_list_cache_time` configuration parameter.
Since the ability to clear these caches is often required by users writing
custom runners which add/remove files, this runner can easily be called
from within a custom runner using any of the following examples:
.. code-block:: python
# Clear all file list caches
__salt__['fileserver.clear_file_list_cache']()
# Clear just the 'base' saltenv file list caches
__salt__['fileserver.clear_file_list_cache'](saltenv='base')
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
__salt__['fileserver.clear_file_list_cache'](saltenv='base', backend='roots')
# Clear all file list caches from the 'roots' fileserver backend
__salt__['fileserver.clear_file_list_cache'](backend='roots')
.. note::
In runners, the ``__salt__`` dictionary will likely be renamed to
``__runner__`` in a future Salt release to distinguish runner functions
from remote execution functions. See `this GitHub issue`_ for
discussion/updates on this.
.. _`this GitHub issue`: https://github.com/saltstack/salt/issues/34958
If using Salt's Python API (not a runner), the following examples are
equivalent to the ones above:
.. code-block:: python
import salt.config
import salt.runner
opts = salt.config.master_config('/etc/salt/master')
opts['fun'] = 'fileserver.clear_file_list_cache'
# Clear all file list_caches
opts['arg'] = [] # No arguments
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches
opts['arg'] = ['base', None]
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
opts['arg'] = ['base', 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
# Clear all file list caches from the 'roots' fileserver backend
opts['arg'] = [None, 'roots']
runner = salt.runner.Runner(opts)
cleared = runner.run()
This function will return a dictionary showing a list of environments which
were cleared for each backend. An empty return dictionary means that no
changes were made.
CLI Examples:
.. code-block:: bash
# Clear all file list caches
salt-run fileserver.clear_file_list_cache
# Clear just the 'base' saltenv file list caches
salt-run fileserver.clear_file_list_cache saltenv=base
# Clear just the 'base' saltenv file list caches from just the 'roots'
# fileserver backend
salt-run fileserver.clear_file_list_cache saltenv=base backend=roots
# Clear all file list caches from the 'roots' fileserver backend
salt-run fileserver.clear_file_list_cache backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.clear_file_list_cache(load=load)
def file_list(saltenv='base', backend=None):
'''
Return a list of files from the salt fileserver
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what files are available to minions.
When in doubt, use :py:func:`cp.list_master
<salt.modules.cp.list_master>` to see what files the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Examples:
.. code-block:: bash
salt-run fileserver.file_list
salt-run fileserver.file_list saltenv=prod
salt-run fileserver.file_list saltenv=dev backend=git
salt-run fileserver.file_list base hg,roots
salt-run fileserver.file_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list(load=load)
def symlink_list(saltenv='base', backend=None):
'''
Return a list of symlinked files and dirs
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what symlinks are available to minions.
When in doubt, use :py:func:`cp.list_master_symlinks
<salt.modules.cp.list_master_symlinks>` to see what symlinks the minion
can see, and always remember to restart the salt-master daemon when
updating the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.symlink_list
salt-run fileserver.symlink_list saltenv=prod
salt-run fileserver.symlink_list saltenv=dev backend=git
salt-run fileserver.symlink_list base hg,roots
salt-run fileserver.symlink_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.symlink_list(load=load)
def dir_list(saltenv='base', backend=None):
'''
Return a list of directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. versionadded:: 2015.5.0
.. note:
Keep in mind that executing this function spawns a new process,
separate from the master. This means that if the fileserver
configuration has been changed in some way since the master has been
restarted (e.g. if :conf_master:`fileserver_backend`,
:conf_master:`gitfs_remotes`, :conf_master:`hgfs_remotes`, etc. have
been updated), then the results of this runner will not accurately
reflect what dirs are available to minions.
When in doubt, use :py:func:`cp.list_master_dirs
<salt.modules.cp.list_master_dirs>` to see what dirs the minion can see,
and always remember to restart the salt-master daemon when updating
the fileserver configuration.
CLI Example:
.. code-block:: bash
salt-run fileserver.dir_list
salt-run fileserver.dir_list saltenv=prod
salt-run fileserver.dir_list saltenv=dev backend=git
salt-run fileserver.dir_list base hg,roots
salt-run fileserver.dir_list -git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.dir_list(load=load)
def empty_dir_list(saltenv='base', backend=None):
'''
.. versionadded:: 2015.5.0
Return a list of empty directories in the given environment
saltenv : base
The salt fileserver environment to be listed
backend
Narrow fileserver backends to a subset of the enabled ones. If all
passed backends start with a minus sign (``-``), then these backends
will be excluded from the enabled backends. However, if there is a mix
of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus sign will
be disregarded.
.. note::
Some backends (such as :mod:`git <salt.fileserver.gitfs>` and
:mod:`hg <salt.fileserver.hgfs>`) do not support empty directories.
So, passing ``backend=git`` or ``backend=hg`` will result in an
empty list being returned.
CLI Example:
.. code-block:: bash
salt-run fileserver.empty_dir_list
salt-run fileserver.empty_dir_list saltenv=prod
salt-run fileserver.empty_dir_list backend=roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
load = {'saltenv': saltenv, 'fsbackend': backend}
return fileserver.file_list_emptydirs(load=load)
def update(backend=None):
'''
Update the fileserver cache. If no backend is provided, then the cache for
all configured backends will be updated.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
If all passed backends start with a minus sign (``-``), then these
backends will be excluded from the enabled backends. However, if
there is a mix of backends with and without a minus sign (ex:
``backend=-roots,git``) then the ones starting with a minus
sign will be disregarded.
Additionally, fileserver backends can now be passed as a
comma-separated list. In earlier versions, they needed to be passed
as a python list (ex: ``backend="['roots', 'git']"``)
CLI Example:
.. code-block:: bash
salt-run fileserver.update
salt-run fileserver.update backend=roots,git
'''
fileserver = salt.fileserver.Fileserver(__opts__)
fileserver.update(back=backend)
return True
def clear_cache(backend=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver cache from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). Executing this runner with no arguments will
clear the cache for all enabled VCS fileserver backends, but this
can be narrowed using the ``backend`` argument.
backend
Only clear the update lock for the specified backend(s). If all passed
backends start with a minus sign (``-``), then these backends will be
excluded from the enabled backends. However, if there is a mix of
backends with and without a minus sign (ex: ``backend=-roots,git``)
then the ones starting with a minus sign will be disregarded.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_cache
salt-run fileserver.clear_cache backend=git,hg
salt-run fileserver.clear_cache hg
salt-run fileserver.clear_cache -roots
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_cache(back=backend)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No cache was cleared'
return ret
def clear_lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
update was interrupted and a remote is not updating (generating a warning
in the Master's log file). Executing this runner with no arguments will
remove all update locks from all enabled VCS fileserver backends, but this
can be narrowed by using the following arguments:
backend
Only clear the update lock for the specified backend(s).
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. For example, a ``remote`` value of **github**
will remove the lock from all github.com remotes.
CLI Example:
.. code-block:: bash
salt-run fileserver.clear_lock
salt-run fileserver.clear_lock backend=git,hg
salt-run fileserver.clear_lock backend=git remote=github
salt-run fileserver.clear_lock remote=bitbucket
'''
fileserver = salt.fileserver.Fileserver(__opts__)
cleared, errors = fileserver.clear_lock(back=backend, remote=remote)
ret = {}
if cleared:
ret['cleared'] = cleared
if errors:
ret['errors'] = errors
if not ret:
return 'No locks were removed'
return ret
|
saltstack/salt
|
salt/key.py
|
KeyCLI.run
|
python
|
def run(self):
'''
Run the logic for saltkey
'''
self._update_opts()
cmd = self.opts['fun']
veri = None
ret = None
try:
if cmd in ('accept', 'reject', 'delete'):
ret = self._run_cmd('name_match')
if not isinstance(ret, dict):
salt.output.display_output(ret, 'key', opts=self.opts)
return ret
ret = self._filter_ret(cmd, ret)
if not ret:
self._print_no_match(cmd, self.opts['match'])
return
print('The following keys are going to be {0}ed:'.format(cmd.rstrip('e')))
salt.output.display_output(ret, 'key', opts=self.opts)
if not self.opts.get('yes', False):
try:
if cmd.startswith('delete'):
veri = input('Proceed? [N/y] ')
if not veri:
veri = 'n'
else:
veri = input('Proceed? [n/Y] ')
if not veri:
veri = 'y'
except KeyboardInterrupt:
raise SystemExit("\nExiting on CTRL-c")
# accept/reject/delete the same keys we're printed to the user
self.opts['match_dict'] = ret
self.opts.pop('match', None)
list_ret = ret
if veri is None or veri.lower().startswith('y'):
ret = self._run_cmd(cmd)
if cmd in ('accept', 'reject', 'delete'):
if cmd == 'delete':
ret = list_ret
for minions in ret.values():
for minion in minions:
print('Key for minion {0} {1}ed.'.format(minion,
cmd.rstrip('e')))
elif isinstance(ret, dict):
salt.output.display_output(ret, 'key', opts=self.opts)
else:
salt.output.display_output({'return': ret}, 'key', opts=self.opts)
except salt.exceptions.SaltException as exc:
ret = '{0}'.format(exc)
if not self.opts.get('quiet', False):
salt.output.display_output(ret, 'nested', self.opts)
return ret
|
Run the logic for saltkey
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L228-L284
|
[
"def display_output(data, out=None, opts=None, **kwargs):\n '''\n Print the passed data using the desired output\n '''\n if opts is None:\n opts = {}\n display_data = try_printout(data, out, opts, **kwargs)\n\n output_filename = opts.get('output_file', None)\n log.trace('data = %s', data)\n try:\n # output filename can be either '' or None\n if output_filename:\n if not hasattr(output_filename, 'write'):\n ofh = salt.utils.files.fopen(output_filename, 'a') # pylint: disable=resource-leakage\n fh_opened = True\n else:\n # Filehandle/file-like object\n ofh = output_filename\n fh_opened = False\n\n try:\n fdata = display_data\n if isinstance(fdata, six.text_type):\n try:\n fdata = fdata.encode('utf-8')\n except (UnicodeDecodeError, UnicodeEncodeError):\n # try to let the stream write\n # even if we didn't encode it\n pass\n if fdata:\n ofh.write(salt.utils.stringutils.to_str(fdata))\n ofh.write('\\n')\n finally:\n if fh_opened:\n ofh.close()\n return\n if display_data:\n salt.utils.stringutils.print_cli(display_data)\n except IOError as exc:\n # Only raise if it's NOT a broken pipe\n if exc.errno != errno.EPIPE:\n raise exc\n",
"def _update_opts(self):\n # get the key command\n for cmd in ('gen_keys',\n 'gen_signature',\n 'list',\n 'list_all',\n 'print',\n 'print_all',\n 'accept',\n 'accept_all',\n 'reject',\n 'reject_all',\n 'delete',\n 'delete_all',\n 'finger',\n 'finger_all',\n 'list_all'): # last is default\n if self.opts[cmd]:\n break\n # set match if needed\n if not cmd.startswith('gen_'):\n if cmd == 'list_all':\n self.opts['match'] = 'all'\n elif cmd.endswith('_all'):\n self.opts['match'] = '*'\n else:\n self.opts['match'] = self.opts[cmd]\n if cmd.startswith('accept'):\n self.opts['include_rejected'] = self.opts['include_all'] or self.opts['include_rejected']\n self.opts['include_accepted'] = False\n elif cmd.startswith('reject'):\n self.opts['include_accepted'] = self.opts['include_all'] or self.opts['include_accepted']\n self.opts['include_rejected'] = False\n elif cmd == 'gen_keys':\n self.opts['keydir'] = self.opts['gen_keys_dir']\n self.opts['keyname'] = self.opts['gen_keys']\n # match is set to opts, now we can forget about *_all commands\n self.opts['fun'] = cmd.replace('_all', '')\n",
"def _run_cmd(self, cmd, args=None):\n if not self.opts.get('eauth'):\n cmd = self.CLI_KEY_MAP.get(cmd, cmd)\n fun = getattr(self.key, cmd)\n args, kwargs = self._get_args_kwargs(fun, args)\n ret = fun(*args, **kwargs)\n if (isinstance(ret, dict) and 'local' in ret and\n cmd not in ('finger', 'finger_all')):\n ret.pop('local', None)\n return ret\n\n fstr = 'key.{0}'.format(cmd)\n fun = self.client.functions[fstr]\n args, kwargs = self._get_args_kwargs(fun, args)\n\n low = {\n 'fun': fstr,\n 'arg': args,\n 'kwarg': kwargs,\n }\n\n self._init_auth()\n low.update(self.auth)\n\n # Execute the key request!\n ret = self.client.cmd_sync(low)\n\n ret = ret['data']['return']\n if (isinstance(ret, dict) and 'local' in ret and\n cmd not in ('finger', 'finger_all')):\n ret.pop('local', None)\n\n return ret\n",
"def _filter_ret(self, cmd, ret):\n if cmd.startswith('delete'):\n return ret\n\n keys = {}\n if self.key.PEND in ret:\n keys[self.key.PEND] = ret[self.key.PEND]\n if self.opts['include_accepted'] and bool(ret.get(self.key.ACC)):\n keys[self.key.ACC] = ret[self.key.ACC]\n if self.opts['include_rejected'] and bool(ret.get(self.key.REJ)):\n keys[self.key.REJ] = ret[self.key.REJ]\n if self.opts['include_denied'] and bool(ret.get(self.key.DEN)):\n keys[self.key.DEN] = ret[self.key.DEN]\n return keys\n",
"def _print_no_match(self, cmd, match):\n statuses = ['unaccepted']\n if self.opts['include_accepted']:\n statuses.append('accepted')\n if self.opts['include_rejected']:\n statuses.append('rejected')\n if self.opts['include_denied']:\n statuses.append('denied')\n if len(statuses) == 1:\n stat_str = statuses[0]\n else:\n stat_str = '{0} or {1}'.format(', '.join(statuses[:-1]), statuses[-1])\n msg = 'The key glob \\'{0}\\' does not match any {1} keys.'.format(match, stat_str)\n print(msg)\n"
] |
class KeyCLI(object):
'''
Manage key CLI operations
'''
CLI_KEY_MAP = {'list': 'list_status',
'delete': 'delete_key',
'gen_signature': 'gen_keys_signature',
'print': 'key_str',
}
def __init__(self, opts):
self.opts = opts
self.client = salt.wheel.WheelClient(opts)
self.key = Key
# instantiate the key object for masterless mode
if not opts.get('eauth'):
self.key = self.key(opts)
self.auth = None
def _update_opts(self):
# get the key command
for cmd in ('gen_keys',
'gen_signature',
'list',
'list_all',
'print',
'print_all',
'accept',
'accept_all',
'reject',
'reject_all',
'delete',
'delete_all',
'finger',
'finger_all',
'list_all'): # last is default
if self.opts[cmd]:
break
# set match if needed
if not cmd.startswith('gen_'):
if cmd == 'list_all':
self.opts['match'] = 'all'
elif cmd.endswith('_all'):
self.opts['match'] = '*'
else:
self.opts['match'] = self.opts[cmd]
if cmd.startswith('accept'):
self.opts['include_rejected'] = self.opts['include_all'] or self.opts['include_rejected']
self.opts['include_accepted'] = False
elif cmd.startswith('reject'):
self.opts['include_accepted'] = self.opts['include_all'] or self.opts['include_accepted']
self.opts['include_rejected'] = False
elif cmd == 'gen_keys':
self.opts['keydir'] = self.opts['gen_keys_dir']
self.opts['keyname'] = self.opts['gen_keys']
# match is set to opts, now we can forget about *_all commands
self.opts['fun'] = cmd.replace('_all', '')
def _init_auth(self):
if self.auth:
return
low = {}
skip_perm_errors = self.opts['eauth'] != ''
if self.opts['eauth']:
if 'token' in self.opts:
try:
with salt.utils.files.fopen(os.path.join(self.opts['cachedir'], '.root_key'), 'r') as fp_:
low['key'] = \
salt.utils.stringutils.to_unicode(fp_.readline())
except IOError:
low['token'] = self.opts['token']
#
# If using eauth and a token hasn't already been loaded into
# low, prompt the user to enter auth credentials
if 'token' not in low and 'key' not in low and self.opts['eauth']:
# This is expensive. Don't do it unless we need to.
resolver = salt.auth.Resolver(self.opts)
res = resolver.cli(self.opts['eauth'])
if self.opts['mktoken'] and res:
tok = resolver.token_cli(
self.opts['eauth'],
res
)
if tok:
low['token'] = tok.get('token', '')
if not res:
log.error('Authentication failed')
return {}
low.update(res)
low['eauth'] = self.opts['eauth']
else:
low['user'] = salt.utils.user.get_specific_user()
low['key'] = salt.utils.master.get_master_key(low['user'], self.opts, skip_perm_errors)
self.auth = low
def _get_args_kwargs(self, fun, args=None):
argspec = salt.utils.args.get_function_argspec(fun)
if args is None:
args = []
if argspec.args:
# Iterate in reverse order to ensure we get the correct default
# value for the positional argument.
for arg, default in zip_longest(reversed(argspec.args),
reversed(argspec.defaults or ())):
args.append(self.opts.get(arg, default))
# Reverse the args so that they are in the correct order
args = args[::-1]
if argspec.keywords is None:
kwargs = {}
else:
args, kwargs = salt.minion.load_args_and_kwargs(
fun,
args)
return args, kwargs
def _run_cmd(self, cmd, args=None):
if not self.opts.get('eauth'):
cmd = self.CLI_KEY_MAP.get(cmd, cmd)
fun = getattr(self.key, cmd)
args, kwargs = self._get_args_kwargs(fun, args)
ret = fun(*args, **kwargs)
if (isinstance(ret, dict) and 'local' in ret and
cmd not in ('finger', 'finger_all')):
ret.pop('local', None)
return ret
fstr = 'key.{0}'.format(cmd)
fun = self.client.functions[fstr]
args, kwargs = self._get_args_kwargs(fun, args)
low = {
'fun': fstr,
'arg': args,
'kwarg': kwargs,
}
self._init_auth()
low.update(self.auth)
# Execute the key request!
ret = self.client.cmd_sync(low)
ret = ret['data']['return']
if (isinstance(ret, dict) and 'local' in ret and
cmd not in ('finger', 'finger_all')):
ret.pop('local', None)
return ret
def _filter_ret(self, cmd, ret):
if cmd.startswith('delete'):
return ret
keys = {}
if self.key.PEND in ret:
keys[self.key.PEND] = ret[self.key.PEND]
if self.opts['include_accepted'] and bool(ret.get(self.key.ACC)):
keys[self.key.ACC] = ret[self.key.ACC]
if self.opts['include_rejected'] and bool(ret.get(self.key.REJ)):
keys[self.key.REJ] = ret[self.key.REJ]
if self.opts['include_denied'] and bool(ret.get(self.key.DEN)):
keys[self.key.DEN] = ret[self.key.DEN]
return keys
def _print_no_match(self, cmd, match):
statuses = ['unaccepted']
if self.opts['include_accepted']:
statuses.append('accepted')
if self.opts['include_rejected']:
statuses.append('rejected')
if self.opts['include_denied']:
statuses.append('denied')
if len(statuses) == 1:
stat_str = statuses[0]
else:
stat_str = '{0} or {1}'.format(', '.join(statuses[:-1]), statuses[-1])
msg = 'The key glob \'{0}\' does not match any {1} keys.'.format(match, stat_str)
print(msg)
|
saltstack/salt
|
salt/key.py
|
Key._check_minions_directories
|
python
|
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
|
Return the minion keys directory paths
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L314-L325
| null |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.gen_keys
|
python
|
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
|
Generate minion RSA public keypair
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L343-L350
|
[
"def gen_keys(keydir, keyname, keysize, user=None, passphrase=None):\n '''\n Generate a RSA public keypair for use with salt\n\n :param str keydir: The directory to write the keypair to\n :param str keyname: The type of salt server for whom this key should be written. (i.e. 'master' or 'minion')\n :param int keysize: The number of bits in the key\n :param str user: The user on the system who should own this keypair\n :param str passphrase: The passphrase which should be used to encrypt the private key\n\n :rtype: str\n :return: Path on the filesystem to the RSA private key\n '''\n base = os.path.join(keydir, keyname)\n priv = '{0}.pem'.format(base)\n pub = '{0}.pub'.format(base)\n\n if HAS_M2:\n gen = RSA.gen_key(keysize, 65537, lambda: None)\n else:\n salt.utils.crypt.reinit_crypto()\n gen = RSA.generate(bits=keysize, e=65537)\n if os.path.isfile(priv):\n # Between first checking and the generation another process has made\n # a key! Use the winner's key\n return priv\n\n # Do not try writing anything, if directory has no permissions.\n if not os.access(keydir, os.W_OK):\n raise IOError('Write access denied to \"{0}\" for user \"{1}\".'.format(os.path.abspath(keydir), getpass.getuser()))\n\n with salt.utils.files.set_umask(0o277):\n if HAS_M2:\n # if passphrase is empty or None use no cipher\n if not passphrase:\n gen.save_pem(priv, cipher=None)\n else:\n gen.save_pem(\n priv,\n cipher='des_ede3_cbc',\n callback=lambda x: salt.utils.stringutils.to_bytes(passphrase))\n else:\n with salt.utils.files.fopen(priv, 'wb+') as f:\n f.write(gen.exportKey('PEM', passphrase))\n if HAS_M2:\n gen.save_pub_key(pub)\n else:\n with salt.utils.files.fopen(pub, 'wb+') as f:\n f.write(gen.publickey().exportKey('PEM'))\n os.chmod(priv, 0o400)\n if user:\n try:\n import pwd\n uid = pwd.getpwnam(user).pw_uid\n os.chown(priv, uid, -1)\n os.chown(pub, uid, -1)\n except (KeyError, ImportError, OSError):\n # The specified user was not found, allow the backup systems to\n # report the error\n pass\n return priv\n",
"def pem_finger(path=None, key=None, sum_type='sha256'):\n '''\n Pass in either a raw pem string, or the path on disk to the location of a\n pem file, and the type of cryptographic hash to use. The default is SHA256.\n The fingerprint of the pem will be returned.\n\n If neither a key nor a path are passed in, a blank string will be returned.\n '''\n if not key:\n if not os.path.isfile(path):\n return ''\n\n with salt.utils.files.fopen(path, 'rb') as fp_:\n key = b''.join([x for x in fp_.readlines() if x.strip()][1:-1])\n\n pre = getattr(hashlib, sum_type)(key).hexdigest()\n finger = ''\n for ind, _ in enumerate(pre):\n if ind % 2:\n # Is odd\n finger += '{0}:'.format(pre[ind])\n else:\n finger += pre[ind]\n return finger.rstrip(':')\n",
"def _get_key_attrs(self, keydir, keyname,\n keysize, user):\n if not keydir:\n if 'gen_keys_dir' in self.opts:\n keydir = self.opts['gen_keys_dir']\n else:\n keydir = self.opts['pki_dir']\n if not keyname:\n if 'gen_keys' in self.opts:\n keyname = self.opts['gen_keys']\n else:\n keyname = 'minion'\n if not keysize:\n keysize = self.opts['keysize']\n return keydir, keyname, keysize, user\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.gen_signature
|
python
|
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
|
Generate master public-key-signature
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L352-L359
|
[
"def gen_signature(priv_path, pub_path, sign_path, passphrase=None):\n '''\n creates a signature for the given public-key with\n the given private key and writes it to sign_path\n '''\n\n with salt.utils.files.fopen(pub_path) as fp_:\n mpub_64 = fp_.read()\n\n mpub_sig = sign_message(priv_path, mpub_64, passphrase)\n mpub_sig_64 = binascii.b2a_base64(mpub_sig)\n if os.path.isfile(sign_path):\n return False\n log.trace(\n 'Calculating signature for %s with %s',\n os.path.basename(pub_path), os.path.basename(priv_path)\n )\n\n if os.path.isfile(sign_path):\n log.trace(\n 'Signature file %s already exists, please remove it first and '\n 'try again', sign_path\n )\n else:\n with salt.utils.files.fopen(sign_path, 'wb+') as sig_f:\n sig_f.write(salt.utils.stringutils.to_bytes(mpub_sig_64))\n log.trace('Wrote signature to %s', sign_path)\n return True\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.gen_keys_signature
|
python
|
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
|
Generate master public-key-signature
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L361-L416
| null |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.check_minion_cache
|
python
|
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
|
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L418-L448
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def factory(opts, **kwargs):\n '''\n Creates and returns the cache class.\n If memory caching is enabled by opts MemCache class will be instantiated.\n If not Cache class will be returned.\n '''\n if opts.get('memcache_expire_seconds', 0):\n cls = MemCache\n else:\n cls = Cache\n return cls(opts, **kwargs)\n",
"def list_keys(self):\n '''\n Return a dict of managed keys and what the key status are\n '''\n key_dirs = self._check_minions_directories()\n\n ret = {}\n\n for dir_ in key_dirs:\n if dir_ is None:\n continue\n ret[os.path.basename(dir_)] = []\n try:\n for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):\n if not fn_.startswith('.'):\n if os.path.isfile(os.path.join(dir_, fn_)):\n ret[os.path.basename(dir_)].append(\n salt.utils.stringutils.to_unicode(fn_)\n )\n except (OSError, IOError):\n # key dir kind is not created yet, just skip\n continue\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.check_master
|
python
|
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
|
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L450-L464
| null |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.name_match
|
python
|
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
|
Accept a glob which to match the of a key and return the key's location
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L466-L490
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def list_keys(self):\n '''\n Return a dict of managed keys and what the key status are\n '''\n key_dirs = self._check_minions_directories()\n\n ret = {}\n\n for dir_ in key_dirs:\n if dir_ is None:\n continue\n ret[os.path.basename(dir_)] = []\n try:\n for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):\n if not fn_.startswith('.'):\n if os.path.isfile(os.path.join(dir_, fn_)):\n ret[os.path.basename(dir_)].append(\n salt.utils.stringutils.to_unicode(fn_)\n )\n except (OSError, IOError):\n # key dir kind is not created yet, just skip\n continue\n return ret\n",
"def all_keys(self):\n '''\n Merge managed keys with local keys\n '''\n keys = self.list_keys()\n keys.update(self.local_keys())\n return keys\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.dict_match
|
python
|
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
|
Accept a dictionary of keys and return the current state of the
specified keys
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L492-L504
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def list_keys(self):\n '''\n Return a dict of managed keys and what the key status are\n '''\n key_dirs = self._check_minions_directories()\n\n ret = {}\n\n for dir_ in key_dirs:\n if dir_ is None:\n continue\n ret[os.path.basename(dir_)] = []\n try:\n for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):\n if not fn_.startswith('.'):\n if os.path.isfile(os.path.join(dir_, fn_)):\n ret[os.path.basename(dir_)].append(\n salt.utils.stringutils.to_unicode(fn_)\n )\n except (OSError, IOError):\n # key dir kind is not created yet, just skip\n continue\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.local_keys
|
python
|
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
|
Return a dict of local keys
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L506-L516
| null |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.list_keys
|
python
|
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
|
Return a dict of managed keys and what the key status are
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L518-L540
|
[
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def _check_minions_directories(self):\n '''\n Return the minion keys directory paths\n '''\n minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)\n minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)\n minions_rejected = os.path.join(self.opts['pki_dir'],\n self.REJ)\n\n minions_denied = os.path.join(self.opts['pki_dir'],\n self.DEN)\n return minions_accepted, minions_pre, minions_rejected, minions_denied\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.all_keys
|
python
|
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
|
Merge managed keys with local keys
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L542-L548
|
[
"def local_keys(self):\n '''\n Return a dict of local keys\n '''\n ret = {'local': []}\n for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):\n if fn_.endswith('.pub') or fn_.endswith('.pem'):\n path = os.path.join(self.opts['pki_dir'], fn_)\n if os.path.isfile(path):\n ret['local'].append(fn_)\n return ret\n",
"def list_keys(self):\n '''\n Return a dict of managed keys and what the key status are\n '''\n key_dirs = self._check_minions_directories()\n\n ret = {}\n\n for dir_ in key_dirs:\n if dir_ is None:\n continue\n ret[os.path.basename(dir_)] = []\n try:\n for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):\n if not fn_.startswith('.'):\n if os.path.isfile(os.path.join(dir_, fn_)):\n ret[os.path.basename(dir_)].append(\n salt.utils.stringutils.to_unicode(fn_)\n )\n except (OSError, IOError):\n # key dir kind is not created yet, just skip\n continue\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.list_status
|
python
|
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
|
Return a dict of managed keys under a named status
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L550-L582
|
[
"def _check_minions_directories(self):\n '''\n Return the minion keys directory paths\n '''\n minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)\n minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)\n minions_rejected = os.path.join(self.opts['pki_dir'],\n self.REJ)\n\n minions_denied = os.path.join(self.opts['pki_dir'],\n self.DEN)\n return minions_accepted, minions_pre, minions_rejected, minions_denied\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.key_str
|
python
|
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
|
Return the specified public key or keys based on a glob
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L584-L596
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def name_match(self, match, full=False):\n '''\n Accept a glob which to match the of a key and return the key's location\n '''\n if full:\n matches = self.all_keys()\n else:\n matches = self.list_keys()\n ret = {}\n if ',' in match and isinstance(match, six.string_types):\n match = match.split(',')\n for status, keys in six.iteritems(matches):\n for key in salt.utils.data.sorted_ignorecase(keys):\n if isinstance(match, list):\n for match_item in match:\n if fnmatch.fnmatch(key, match_item):\n if status not in ret:\n ret[status] = []\n ret[status].append(key)\n else:\n if fnmatch.fnmatch(key, match):\n if status not in ret:\n ret[status] = []\n ret[status].append(key)\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.accept
|
python
|
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
|
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L612-L651
|
[
"def tagify(suffix='', prefix='', base=SALT):\n '''\n convenience function to build a namespaced event tag string\n from joining with the TABPART character the base, prefix and suffix\n\n If string prefix is a valid key in TAGS Then use the value of key prefix\n Else use prefix string\n\n If suffix is a list Then join all string elements of suffix individually\n Else use string suffix\n\n '''\n parts = [base, TAGS.get(prefix, prefix)]\n if hasattr(suffix, 'append'): # list so extend parts\n parts.extend(suffix)\n else: # string so append\n parts.append(suffix)\n\n for index, _ in enumerate(parts):\n try:\n parts[index] = salt.utils.stringutils.to_str(parts[index])\n except TypeError:\n parts[index] = str(parts[index])\n return TAGPARTER.join([part for part in parts if part])\n",
"def name_match(self, match, full=False):\n '''\n Accept a glob which to match the of a key and return the key's location\n '''\n if full:\n matches = self.all_keys()\n else:\n matches = self.list_keys()\n ret = {}\n if ',' in match and isinstance(match, six.string_types):\n match = match.split(',')\n for status, keys in six.iteritems(matches):\n for key in salt.utils.data.sorted_ignorecase(keys):\n if isinstance(match, list):\n for match_item in match:\n if fnmatch.fnmatch(key, match_item):\n if status not in ret:\n ret[status] = []\n ret[status].append(key)\n else:\n if fnmatch.fnmatch(key, match):\n if status not in ret:\n ret[status] = []\n ret[status].append(key)\n return ret\n",
"def dict_match(self, match_dict):\n '''\n Accept a dictionary of keys and return the current state of the\n specified keys\n '''\n ret = {}\n cur_keys = self.list_keys()\n for status, keys in six.iteritems(match_dict):\n for key in salt.utils.data.sorted_ignorecase(keys):\n for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):\n if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):\n ret.setdefault(keydir, []).append(key)\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.accept_all
|
python
|
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
|
Accept all keys in pre
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L653-L677
|
[
"def tagify(suffix='', prefix='', base=SALT):\n '''\n convenience function to build a namespaced event tag string\n from joining with the TABPART character the base, prefix and suffix\n\n If string prefix is a valid key in TAGS Then use the value of key prefix\n Else use prefix string\n\n If suffix is a list Then join all string elements of suffix individually\n Else use string suffix\n\n '''\n parts = [base, TAGS.get(prefix, prefix)]\n if hasattr(suffix, 'append'): # list so extend parts\n parts.extend(suffix)\n else: # string so append\n parts.append(suffix)\n\n for index, _ in enumerate(parts):\n try:\n parts[index] = salt.utils.stringutils.to_str(parts[index])\n except TypeError:\n parts[index] = str(parts[index])\n return TAGPARTER.join([part for part in parts if part])\n",
"def list_keys(self):\n '''\n Return a dict of managed keys and what the key status are\n '''\n key_dirs = self._check_minions_directories()\n\n ret = {}\n\n for dir_ in key_dirs:\n if dir_ is None:\n continue\n ret[os.path.basename(dir_)] = []\n try:\n for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):\n if not fn_.startswith('.'):\n if os.path.isfile(os.path.join(dir_, fn_)):\n ret[os.path.basename(dir_)].append(\n salt.utils.stringutils.to_unicode(fn_)\n )\n except (OSError, IOError):\n # key dir kind is not created yet, just skip\n continue\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.delete_key
|
python
|
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
|
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L679-L729
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def get_local_client(\n c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),\n mopts=None,\n skip_perm_errors=False,\n io_loop=None,\n auto_reconnect=False):\n '''\n .. versionadded:: 2014.7.0\n\n Read in the config and return the correct LocalClient object based on\n the configured transport\n\n :param IOLoop io_loop: io_loop used for events.\n Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n if mopts:\n opts = mopts\n else:\n # Late import to prevent circular import\n import salt.config\n opts = salt.config.client_config(c_path)\n\n # TODO: AIO core is separate from transport\n return LocalClient(\n mopts=opts,\n skip_perm_errors=skip_perm_errors,\n io_loop=io_loop,\n auto_reconnect=auto_reconnect)\n",
"def tagify(suffix='', prefix='', base=SALT):\n '''\n convenience function to build a namespaced event tag string\n from joining with the TABPART character the base, prefix and suffix\n\n If string prefix is a valid key in TAGS Then use the value of key prefix\n Else use prefix string\n\n If suffix is a list Then join all string elements of suffix individually\n Else use string suffix\n\n '''\n parts = [base, TAGS.get(prefix, prefix)]\n if hasattr(suffix, 'append'): # list so extend parts\n parts.extend(suffix)\n else: # string so append\n parts.append(suffix)\n\n for index, _ in enumerate(parts):\n try:\n parts[index] = salt.utils.stringutils.to_str(parts[index])\n except TypeError:\n parts[index] = str(parts[index])\n return TAGPARTER.join([part for part in parts if part])\n",
"def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n",
"def name_match(self, match, full=False):\n '''\n Accept a glob which to match the of a key and return the key's location\n '''\n if full:\n matches = self.all_keys()\n else:\n matches = self.list_keys()\n ret = {}\n if ',' in match and isinstance(match, six.string_types):\n match = match.split(',')\n for status, keys in six.iteritems(matches):\n for key in salt.utils.data.sorted_ignorecase(keys):\n if isinstance(match, list):\n for match_item in match:\n if fnmatch.fnmatch(key, match_item):\n if status not in ret:\n ret[status] = []\n ret[status].append(key)\n else:\n if fnmatch.fnmatch(key, match):\n if status not in ret:\n ret[status] = []\n ret[status].append(key)\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.delete_den
|
python
|
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
|
Delete all denied keys
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L731-L748
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def tagify(suffix='', prefix='', base=SALT):\n '''\n convenience function to build a namespaced event tag string\n from joining with the TABPART character the base, prefix and suffix\n\n If string prefix is a valid key in TAGS Then use the value of key prefix\n Else use prefix string\n\n If suffix is a list Then join all string elements of suffix individually\n Else use string suffix\n\n '''\n parts = [base, TAGS.get(prefix, prefix)]\n if hasattr(suffix, 'append'): # list so extend parts\n parts.extend(suffix)\n else: # string so append\n parts.append(suffix)\n\n for index, _ in enumerate(parts):\n try:\n parts[index] = salt.utils.stringutils.to_str(parts[index])\n except TypeError:\n parts[index] = str(parts[index])\n return TAGPARTER.join([part for part in parts if part])\n",
"def check_minion_cache(self, preserve_minions=None):\n '''\n Check the minion cache to make sure that old minion data is cleared\n\n Optionally, pass in a list of minions which should have their caches\n preserved. To preserve all caches, set __opts__['preserve_minion_cache']\n '''\n if preserve_minions is None:\n preserve_minions = []\n keys = self.list_keys()\n minions = []\n for key, val in six.iteritems(keys):\n minions.extend(val)\n if not self.opts.get('preserve_minion_cache', False):\n m_cache = os.path.join(self.opts['cachedir'], self.ACC)\n if os.path.isdir(m_cache):\n for minion in os.listdir(m_cache):\n if minion not in minions and minion not in preserve_minions:\n try:\n shutil.rmtree(os.path.join(m_cache, minion))\n except (OSError, IOError) as ex:\n log.warning('Key: Delete cache for %s got OSError/IOError: %s \\n',\n minion,\n ex)\n continue\n cache = salt.cache.factory(self.opts)\n clist = cache.list(self.ACC)\n if clist:\n for minion in clist:\n if minion not in minions and minion not in preserve_minions:\n cache.flush('{0}/{1}'.format(self.ACC, minion))\n",
"def list_keys(self):\n '''\n Return a dict of managed keys and what the key status are\n '''\n key_dirs = self._check_minions_directories()\n\n ret = {}\n\n for dir_ in key_dirs:\n if dir_ is None:\n continue\n ret[os.path.basename(dir_)] = []\n try:\n for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):\n if not fn_.startswith('.'):\n if os.path.isfile(os.path.join(dir_, fn_)):\n ret[os.path.basename(dir_)].append(\n salt.utils.stringutils.to_unicode(fn_)\n )\n except (OSError, IOError):\n # key dir kind is not created yet, just skip\n continue\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.delete_all
|
python
|
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
|
Delete all keys
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L750-L768
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def tagify(suffix='', prefix='', base=SALT):\n '''\n convenience function to build a namespaced event tag string\n from joining with the TABPART character the base, prefix and suffix\n\n If string prefix is a valid key in TAGS Then use the value of key prefix\n Else use prefix string\n\n If suffix is a list Then join all string elements of suffix individually\n Else use string suffix\n\n '''\n parts = [base, TAGS.get(prefix, prefix)]\n if hasattr(suffix, 'append'): # list so extend parts\n parts.extend(suffix)\n else: # string so append\n parts.append(suffix)\n\n for index, _ in enumerate(parts):\n try:\n parts[index] = salt.utils.stringutils.to_str(parts[index])\n except TypeError:\n parts[index] = str(parts[index])\n return TAGPARTER.join([part for part in parts if part])\n",
"def dropfile(cachedir, user=None):\n '''\n Set an AES dropfile to request the master update the publish session key\n '''\n dfn = os.path.join(cachedir, '.dfn')\n # set a mask (to avoid a race condition on file creation) and store original.\n with salt.utils.files.set_umask(0o277):\n log.info('Rotating AES key')\n if os.path.isfile(dfn):\n log.info('AES key rotation already requested')\n return\n\n if os.path.isfile(dfn) and not os.access(dfn, os.W_OK):\n os.chmod(dfn, stat.S_IRUSR | stat.S_IWUSR)\n with salt.utils.files.fopen(dfn, 'wb+') as fp_:\n fp_.write(b'')\n os.chmod(dfn, stat.S_IRUSR)\n if user:\n try:\n import pwd\n uid = pwd.getpwnam(user).pw_uid\n os.chown(dfn, uid, -1)\n except (KeyError, ImportError, OSError, IOError):\n pass\n",
"def check_minion_cache(self, preserve_minions=None):\n '''\n Check the minion cache to make sure that old minion data is cleared\n\n Optionally, pass in a list of minions which should have their caches\n preserved. To preserve all caches, set __opts__['preserve_minion_cache']\n '''\n if preserve_minions is None:\n preserve_minions = []\n keys = self.list_keys()\n minions = []\n for key, val in six.iteritems(keys):\n minions.extend(val)\n if not self.opts.get('preserve_minion_cache', False):\n m_cache = os.path.join(self.opts['cachedir'], self.ACC)\n if os.path.isdir(m_cache):\n for minion in os.listdir(m_cache):\n if minion not in minions and minion not in preserve_minions:\n try:\n shutil.rmtree(os.path.join(m_cache, minion))\n except (OSError, IOError) as ex:\n log.warning('Key: Delete cache for %s got OSError/IOError: %s \\n',\n minion,\n ex)\n continue\n cache = salt.cache.factory(self.opts)\n clist = cache.list(self.ACC)\n if clist:\n for minion in clist:\n if minion not in minions and minion not in preserve_minions:\n cache.flush('{0}/{1}'.format(self.ACC, minion))\n",
"def list_keys(self):\n '''\n Return a dict of managed keys and what the key status are\n '''\n key_dirs = self._check_minions_directories()\n\n ret = {}\n\n for dir_ in key_dirs:\n if dir_ is None:\n continue\n ret[os.path.basename(dir_)] = []\n try:\n for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):\n if not fn_.startswith('.'):\n if os.path.isfile(os.path.join(dir_, fn_)):\n ret[os.path.basename(dir_)].append(\n salt.utils.stringutils.to_unicode(fn_)\n )\n except (OSError, IOError):\n # key dir kind is not created yet, just skip\n continue\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.reject_all
|
python
|
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
|
Reject all keys in pre
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L814-L841
|
[
"def tagify(suffix='', prefix='', base=SALT):\n '''\n convenience function to build a namespaced event tag string\n from joining with the TABPART character the base, prefix and suffix\n\n If string prefix is a valid key in TAGS Then use the value of key prefix\n Else use prefix string\n\n If suffix is a list Then join all string elements of suffix individually\n Else use string suffix\n\n '''\n parts = [base, TAGS.get(prefix, prefix)]\n if hasattr(suffix, 'append'): # list so extend parts\n parts.extend(suffix)\n else: # string so append\n parts.append(suffix)\n\n for index, _ in enumerate(parts):\n try:\n parts[index] = salt.utils.stringutils.to_str(parts[index])\n except TypeError:\n parts[index] = str(parts[index])\n return TAGPARTER.join([part for part in parts if part])\n",
"def dropfile(cachedir, user=None):\n '''\n Set an AES dropfile to request the master update the publish session key\n '''\n dfn = os.path.join(cachedir, '.dfn')\n # set a mask (to avoid a race condition on file creation) and store original.\n with salt.utils.files.set_umask(0o277):\n log.info('Rotating AES key')\n if os.path.isfile(dfn):\n log.info('AES key rotation already requested')\n return\n\n if os.path.isfile(dfn) and not os.access(dfn, os.W_OK):\n os.chmod(dfn, stat.S_IRUSR | stat.S_IWUSR)\n with salt.utils.files.fopen(dfn, 'wb+') as fp_:\n fp_.write(b'')\n os.chmod(dfn, stat.S_IRUSR)\n if user:\n try:\n import pwd\n uid = pwd.getpwnam(user).pw_uid\n os.chown(dfn, uid, -1)\n except (KeyError, ImportError, OSError, IOError):\n pass\n",
"def check_minion_cache(self, preserve_minions=None):\n '''\n Check the minion cache to make sure that old minion data is cleared\n\n Optionally, pass in a list of minions which should have their caches\n preserved. To preserve all caches, set __opts__['preserve_minion_cache']\n '''\n if preserve_minions is None:\n preserve_minions = []\n keys = self.list_keys()\n minions = []\n for key, val in six.iteritems(keys):\n minions.extend(val)\n if not self.opts.get('preserve_minion_cache', False):\n m_cache = os.path.join(self.opts['cachedir'], self.ACC)\n if os.path.isdir(m_cache):\n for minion in os.listdir(m_cache):\n if minion not in minions and minion not in preserve_minions:\n try:\n shutil.rmtree(os.path.join(m_cache, minion))\n except (OSError, IOError) as ex:\n log.warning('Key: Delete cache for %s got OSError/IOError: %s \\n',\n minion,\n ex)\n continue\n cache = salt.cache.factory(self.opts)\n clist = cache.list(self.ACC)\n if clist:\n for minion in clist:\n if minion not in minions and minion not in preserve_minions:\n cache.flush('{0}/{1}'.format(self.ACC, minion))\n",
"def list_keys(self):\n '''\n Return a dict of managed keys and what the key status are\n '''\n key_dirs = self._check_minions_directories()\n\n ret = {}\n\n for dir_ in key_dirs:\n if dir_ is None:\n continue\n ret[os.path.basename(dir_)] = []\n try:\n for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):\n if not fn_.startswith('.'):\n if os.path.isfile(os.path.join(dir_, fn_)):\n ret[os.path.basename(dir_)].append(\n salt.utils.stringutils.to_unicode(fn_)\n )\n except (OSError, IOError):\n # key dir kind is not created yet, just skip\n continue\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.finger
|
python
|
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
Return the fingerprint for a specified key
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L843-L860
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def pem_finger(path=None, key=None, sum_type='sha256'):\n '''\n Pass in either a raw pem string, or the path on disk to the location of a\n pem file, and the type of cryptographic hash to use. The default is SHA256.\n The fingerprint of the pem will be returned.\n\n If neither a key nor a path are passed in, a blank string will be returned.\n '''\n if not key:\n if not os.path.isfile(path):\n return ''\n\n with salt.utils.files.fopen(path, 'rb') as fp_:\n key = b''.join([x for x in fp_.readlines() if x.strip()][1:-1])\n\n pre = getattr(hashlib, sum_type)(key).hexdigest()\n finger = ''\n for ind, _ in enumerate(pre):\n if ind % 2:\n # Is odd\n finger += '{0}:'.format(pre[ind])\n else:\n finger += pre[ind]\n return finger.rstrip(':')\n",
"def name_match(self, match, full=False):\n '''\n Accept a glob which to match the of a key and return the key's location\n '''\n if full:\n matches = self.all_keys()\n else:\n matches = self.list_keys()\n ret = {}\n if ',' in match and isinstance(match, six.string_types):\n match = match.split(',')\n for status, keys in six.iteritems(matches):\n for key in salt.utils.data.sorted_ignorecase(keys):\n if isinstance(match, list):\n for match_item in match:\n if fnmatch.fnmatch(key, match_item):\n if status not in ret:\n ret[status] = []\n ret[status].append(key)\n else:\n if fnmatch.fnmatch(key, match):\n if status not in ret:\n ret[status] = []\n ret[status].append(key)\n return ret\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/key.py
|
Key.finger_all
|
python
|
def finger_all(self, hash_type=None):
'''
Return fingerprints for all keys
'''
if hash_type is None:
hash_type = __opts__['hash_type']
ret = {}
for status, keys in six.iteritems(self.all_keys()):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
Return fingerprints for all keys
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/key.py#L862-L878
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def pem_finger(path=None, key=None, sum_type='sha256'):\n '''\n Pass in either a raw pem string, or the path on disk to the location of a\n pem file, and the type of cryptographic hash to use. The default is SHA256.\n The fingerprint of the pem will be returned.\n\n If neither a key nor a path are passed in, a blank string will be returned.\n '''\n if not key:\n if not os.path.isfile(path):\n return ''\n\n with salt.utils.files.fopen(path, 'rb') as fp_:\n key = b''.join([x for x in fp_.readlines() if x.strip()][1:-1])\n\n pre = getattr(hashlib, sum_type)(key).hexdigest()\n finger = ''\n for ind, _ in enumerate(pre):\n if ind % 2:\n # Is odd\n finger += '{0}:'.format(pre[ind])\n else:\n finger += pre[ind]\n return finger.rstrip(':')\n",
"def all_keys(self):\n '''\n Merge managed keys with local keys\n '''\n keys = self.list_keys()\n keys.update(self.local_keys())\n return keys\n"
] |
class Key(object):
'''
The object that encapsulates saltkey actions
'''
ACC = 'minions'
PEND = 'minions_pre'
REJ = 'minions_rejected'
DEN = 'minions_denied'
def __init__(self, opts, io_loop=None):
self.opts = opts
kind = self.opts.get('__role', '') # application kind
if kind not in salt.utils.kinds.APPL_KINDS:
emsg = "Invalid application kind = '{0}'.".format(kind)
log.error(emsg)
raise ValueError(emsg)
self.event = salt.utils.event.get_event(
kind,
opts['sock_dir'],
opts['transport'],
opts=opts,
listen=False,
io_loop=io_loop
)
self.passphrase = salt.utils.sdb.sdb_get(self.opts.get('signing_key_pass'), self.opts)
def _check_minions_directories(self):
'''
Return the minion keys directory paths
'''
minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC)
minions_pre = os.path.join(self.opts['pki_dir'], self.PEND)
minions_rejected = os.path.join(self.opts['pki_dir'],
self.REJ)
minions_denied = os.path.join(self.opts['pki_dir'],
self.DEN)
return minions_accepted, minions_pre, minions_rejected, minions_denied
def _get_key_attrs(self, keydir, keyname,
keysize, user):
if not keydir:
if 'gen_keys_dir' in self.opts:
keydir = self.opts['gen_keys_dir']
else:
keydir = self.opts['pki_dir']
if not keyname:
if 'gen_keys' in self.opts:
keyname = self.opts['gen_keys']
else:
keyname = 'minion'
if not keysize:
keysize = self.opts['keysize']
return keydir, keyname, keysize, user
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
'''
Generate minion RSA public keypair
'''
keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname,
keysize, user)
salt.crypt.gen_keys(keydir, keyname, keysize, user, self.passphrase)
return salt.utils.crypt.pem_finger(os.path.join(keydir, keyname + '.pub'))
def gen_signature(self, privkey, pubkey, sig_path):
'''
Generate master public-key-signature
'''
return salt.crypt.gen_signature(privkey,
pubkey,
sig_path,
self.passphrase)
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
# check given pub-key
if pub:
if not os.path.isfile(pub):
return 'Public-key {0} does not exist'.format(pub)
# default to master.pub
else:
mpub = self.opts['pki_dir'] + '/' + 'master.pub'
if os.path.isfile(mpub):
pub = mpub
# check given priv-key
if priv:
if not os.path.isfile(priv):
return 'Private-key {0} does not exist'.format(priv)
# default to master_sign.pem
else:
mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
if os.path.isfile(mpriv):
priv = mpriv
if not priv:
if auto_create:
log.debug(
'Generating new signing key-pair .%s.* in %s',
self.opts['master_sign_key_name'], self.opts['pki_dir']
)
salt.crypt.gen_keys(self.opts['pki_dir'],
self.opts['master_sign_key_name'],
keysize or self.opts['keysize'],
self.opts.get('user'),
self.passphrase)
priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
else:
return 'No usable private-key found'
if not pub:
return 'No usable public-key found'
log.debug('Using public-key %s', pub)
log.debug('Using private-key %s', priv)
if signature_path:
if not os.path.isdir(signature_path):
log.debug('target directory %s does not exist', signature_path)
else:
signature_path = self.opts['pki_dir']
sign_path = signature_path + '/' + self.opts['master_pubkey_signature']
skey = get_key(self.opts)
return skey.gen_signature(priv, pub, sign_path)
def check_minion_cache(self, preserve_minions=None):
'''
Check the minion cache to make sure that old minion data is cleared
Optionally, pass in a list of minions which should have their caches
preserved. To preserve all caches, set __opts__['preserve_minion_cache']
'''
if preserve_minions is None:
preserve_minions = []
keys = self.list_keys()
minions = []
for key, val in six.iteritems(keys):
minions.extend(val)
if not self.opts.get('preserve_minion_cache', False):
m_cache = os.path.join(self.opts['cachedir'], self.ACC)
if os.path.isdir(m_cache):
for minion in os.listdir(m_cache):
if minion not in minions and minion not in preserve_minions:
try:
shutil.rmtree(os.path.join(m_cache, minion))
except (OSError, IOError) as ex:
log.warning('Key: Delete cache for %s got OSError/IOError: %s \n',
minion,
ex)
continue
cache = salt.cache.factory(self.opts)
clist = cache.list(self.ACC)
if clist:
for minion in clist:
if minion not in minions and minion not in preserve_minions:
cache.flush('{0}/{1}'.format(self.ACC, minion))
def check_master(self):
'''
Log if the master is not running
:rtype: bool
:return: Whether or not the master is running
'''
if not os.path.exists(
os.path.join(
self.opts['sock_dir'],
'publish_pull.ipc'
)
):
return False
return True
def name_match(self, match, full=False):
'''
Accept a glob which to match the of a key and return the key's location
'''
if full:
matches = self.all_keys()
else:
matches = self.list_keys()
ret = {}
if ',' in match and isinstance(match, six.string_types):
match = match.split(',')
for status, keys in six.iteritems(matches):
for key in salt.utils.data.sorted_ignorecase(keys):
if isinstance(match, list):
for match_item in match:
if fnmatch.fnmatch(key, match_item):
if status not in ret:
ret[status] = []
ret[status].append(key)
else:
if fnmatch.fnmatch(key, match):
if status not in ret:
ret[status] = []
ret[status].append(key)
return ret
def dict_match(self, match_dict):
'''
Accept a dictionary of keys and return the current state of the
specified keys
'''
ret = {}
cur_keys = self.list_keys()
for status, keys in six.iteritems(match_dict):
for key in salt.utils.data.sorted_ignorecase(keys):
for keydir in (self.ACC, self.PEND, self.REJ, self.DEN):
if keydir and fnmatch.filter(cur_keys.get(keydir, []), key):
ret.setdefault(keydir, []).append(key)
return ret
def local_keys(self):
'''
Return a dict of local keys
'''
ret = {'local': []}
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(self.opts['pki_dir'])):
if fn_.endswith('.pub') or fn_.endswith('.pem'):
path = os.path.join(self.opts['pki_dir'], fn_)
if os.path.isfile(path):
ret['local'].append(fn_)
return ret
def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
# key dir kind is not created yet, just skip
continue
return ret
def all_keys(self):
'''
Merge managed keys with local keys
'''
keys = self.list_keys()
keys.update(self.local_keys())
return keys
def list_status(self, match):
'''
Return a dict of managed keys under a named status
'''
acc, pre, rej, den = self._check_minions_directories()
ret = {}
if match.startswith('acc'):
ret[os.path.basename(acc)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(acc)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(acc, fn_)):
ret[os.path.basename(acc)].append(fn_)
elif match.startswith('pre') or match.startswith('un'):
ret[os.path.basename(pre)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(pre)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(pre, fn_)):
ret[os.path.basename(pre)].append(fn_)
elif match.startswith('rej'):
ret[os.path.basename(rej)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(rej)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(rej, fn_)):
ret[os.path.basename(rej)].append(fn_)
elif match.startswith('den') and den is not None:
ret[os.path.basename(den)] = []
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(den)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(den, fn_)):
ret[os.path.basename(den)].append(fn_)
elif match.startswith('all'):
return self.all_keys()
return ret
def key_str(self, match):
'''
Return the specified public key or keys based on a glob
'''
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def key_str_all(self):
'''
Return all managed key strings
'''
ret = {}
for status, keys in six.iteritems(self.list_keys()):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_rejected:
keydirs.append(self.REJ)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.ACC,
key)
)
eload = {'result': True,
'act': 'accept',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
return self.list_keys()
def delete_key(self,
match=None,
match_dict=None,
preserve_minions=None,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
To preserve the master caches of minions who are matched, set preserve_minions
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
for status, keys in six.iteritems(matches):
for key in keys:
try:
if revoke_auth:
if self.opts.get('rotate_aes_key') is False:
print('Immediate auth revocation specified but AES key rotation not allowed. '
'Minion will not be disconnected until the master AES key is rotated.')
else:
try:
client = salt.client.get_local_client(mopts=self.opts)
client.cmd_async(key, 'saltutil.revoke_auth')
except salt.exceptions.SaltClientError:
print('Cannot contact Salt master. '
'Connection for {0} will remain up until '
'master AES key is rotated or auth is revoked '
'with \'saltutil.revoke_auth\'.'.format(key))
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
if self.opts.get('preserve_minions') is True:
self.check_minion_cache(preserve_minions=matches.get('minions', []))
else:
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
return self.list_keys()
def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
'act': 'delete',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (OSError, IOError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.name_match(match)
elif match_dict is not None and isinstance(match_dict, dict):
matches = match_dict
else:
matches = {}
keydirs = [self.PEND]
if include_accepted:
keydirs.append(self.ACC)
if include_denied:
keydirs.append(self.DEN)
for keydir in keydirs:
for key in matches.get(keydir, []):
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
keydir,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return (
self.name_match(match) if match is not None
else self.dict_match(matches)
)
def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
key),
os.path.join(
self.opts['pki_dir'],
self.REJ,
key)
)
eload = {'result': True,
'act': 'reject',
'id': key}
self.event.fire_event(eload,
salt.utils.event.tagify(prefix='key'))
except (IOError, OSError):
pass
self.check_minion_cache()
if self.opts.get('rotate_aes_key'):
salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
return self.list_keys()
def finger(self, match, hash_type=None):
'''
Return the fingerprint for a specified key
'''
if hash_type is None:
hash_type = __opts__['hash_type']
matches = self.name_match(match, True)
ret = {}
for status, keys in six.iteritems(matches):
ret[status] = {}
for key in keys:
if status == 'local':
path = os.path.join(self.opts['pki_dir'], key)
else:
path = os.path.join(self.opts['pki_dir'], status, key)
ret[status][key] = salt.utils.crypt.pem_finger(path, sum_type=hash_type)
return ret
|
saltstack/salt
|
salt/modules/tomcat.py
|
__catalina_home
|
python
|
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
|
Tomcat paths differ depending on packaging
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L119-L130
| null |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
_get_credentials
|
python
|
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
|
Get the username and password from opts, grains, or pillar
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L133-L156
| null |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
_auth
|
python
|
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
|
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L159-L178
| null |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
extract_war_version
|
python
|
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None
|
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L181-L198
| null |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
# default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
_wget
|
python
|
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
|
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L201-L265
|
[
"def _auth(uri):\n '''\n returns a authentication handler.\n Get user & password from grains, if are not set default to\n modules.config.option\n\n If user & pass are missing return False\n '''\n\n user, password = _get_credentials()\n if user is False or password is False:\n return False\n\n basic = _HTTPBasicAuthHandler()\n basic.add_password(realm='Tomcat Manager Application', uri=uri,\n user=user, passwd=password)\n digest = _HTTPDigestAuthHandler()\n digest.add_password(realm='Tomcat Manager Application', uri=uri,\n user=user, passwd=password)\n return _build_opener(basic, digest)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
_simple_cmd
|
python
|
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
|
Simple command wrapper to commands that need only a path option
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L268-L280
|
[
"def ls(url='http://localhost:8080/manager', timeout=180):\n '''\n list all the deployed webapps\n\n url : http://localhost:8080/manager\n the URL of the server manager webapp\n timeout : 180\n timeout for HTTP request\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' tomcat.ls\n salt '*' tomcat.ls http://localhost:8080/manager\n '''\n\n ret = {}\n data = _wget('list', '', url, timeout=timeout)\n if data['res'] is False:\n return {}\n data['msg'].pop(0)\n for line in data['msg']:\n tmp = line.split(':')\n ret[tmp[0]] = {\n 'mode': tmp[1],\n 'sessions': tmp[2],\n 'fullname': tmp[3],\n 'version': '',\n }\n sliced = tmp[3].split('##')\n if len(sliced) > 1:\n ret[tmp[0]]['version'] = sliced[1]\n\n return ret\n",
"def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):\n '''\n A private function used to issue the command to tomcat via the manager\n webapp\n\n cmd\n the command to execute\n\n url\n The URL of the server manager webapp (example:\n http://localhost:8080/manager)\n\n opts\n a dict of arguments\n\n timeout\n timeout for HTTP request\n\n Return value is a dict in the from of::\n\n {\n res: [True|False]\n msg: list of lines we got back from the manager\n }\n '''\n\n ret = {\n 'res': True,\n 'msg': []\n }\n\n # prepare authentication\n auth = _auth(url)\n if auth is False:\n ret['res'] = False\n ret['msg'] = 'missing username and password settings (grain/pillar)'\n return ret\n\n # prepare URL\n if url[-1] != '/':\n url += '/'\n url6 = url\n url += 'text/{0}'.format(cmd)\n url6 += '{0}'.format(cmd)\n if opts:\n url += '?{0}'.format(_urlencode(opts))\n url6 += '?{0}'.format(_urlencode(opts))\n\n # Make the HTTP request\n _install_opener(auth)\n\n try:\n # Trying tomcat >= 7 url\n ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()\n except Exception:\n try:\n # Trying tomcat6 url\n ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()\n except Exception:\n ret['msg'] = 'Failed to create HTTP request'\n\n if not ret['msg'][0].startswith('OK'):\n ret['res'] = False\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
ls
|
python
|
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
|
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L324-L358
|
[
"def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):\n '''\n A private function used to issue the command to tomcat via the manager\n webapp\n\n cmd\n the command to execute\n\n url\n The URL of the server manager webapp (example:\n http://localhost:8080/manager)\n\n opts\n a dict of arguments\n\n timeout\n timeout for HTTP request\n\n Return value is a dict in the from of::\n\n {\n res: [True|False]\n msg: list of lines we got back from the manager\n }\n '''\n\n ret = {\n 'res': True,\n 'msg': []\n }\n\n # prepare authentication\n auth = _auth(url)\n if auth is False:\n ret['res'] = False\n ret['msg'] = 'missing username and password settings (grain/pillar)'\n return ret\n\n # prepare URL\n if url[-1] != '/':\n url += '/'\n url6 = url\n url += 'text/{0}'.format(cmd)\n url6 += '{0}'.format(cmd)\n if opts:\n url += '?{0}'.format(_urlencode(opts))\n url6 += '?{0}'.format(_urlencode(opts))\n\n # Make the HTTP request\n _install_opener(auth)\n\n try:\n # Trying tomcat >= 7 url\n ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()\n except Exception:\n try:\n # Trying tomcat6 url\n ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()\n except Exception:\n ret['msg'] = 'Failed to create HTTP request'\n\n if not ret['msg'][0].startswith('OK'):\n ret['res'] = False\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
status_webapp
|
python
|
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
|
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L449-L473
|
[
"def ls(url='http://localhost:8080/manager', timeout=180):\n '''\n list all the deployed webapps\n\n url : http://localhost:8080/manager\n the URL of the server manager webapp\n timeout : 180\n timeout for HTTP request\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' tomcat.ls\n salt '*' tomcat.ls http://localhost:8080/manager\n '''\n\n ret = {}\n data = _wget('list', '', url, timeout=timeout)\n if data['res'] is False:\n return {}\n data['msg'].pop(0)\n for line in data['msg']:\n tmp = line.split(':')\n ret[tmp[0]] = {\n 'mode': tmp[1],\n 'sessions': tmp[2],\n 'fullname': tmp[3],\n 'version': '',\n }\n sliced = tmp[3].split('##')\n if len(sliced) > 1:\n ret[tmp[0]]['version'] = sliced[1]\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
serverinfo
|
python
|
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
|
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L476-L503
|
[
"def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):\n '''\n A private function used to issue the command to tomcat via the manager\n webapp\n\n cmd\n the command to execute\n\n url\n The URL of the server manager webapp (example:\n http://localhost:8080/manager)\n\n opts\n a dict of arguments\n\n timeout\n timeout for HTTP request\n\n Return value is a dict in the from of::\n\n {\n res: [True|False]\n msg: list of lines we got back from the manager\n }\n '''\n\n ret = {\n 'res': True,\n 'msg': []\n }\n\n # prepare authentication\n auth = _auth(url)\n if auth is False:\n ret['res'] = False\n ret['msg'] = 'missing username and password settings (grain/pillar)'\n return ret\n\n # prepare URL\n if url[-1] != '/':\n url += '/'\n url6 = url\n url += 'text/{0}'.format(cmd)\n url6 += '{0}'.format(cmd)\n if opts:\n url += '?{0}'.format(_urlencode(opts))\n url6 += '?{0}'.format(_urlencode(opts))\n\n # Make the HTTP request\n _install_opener(auth)\n\n try:\n # Trying tomcat >= 7 url\n ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()\n except Exception:\n try:\n # Trying tomcat6 url\n ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()\n except Exception:\n ret['msg'] = 'Failed to create HTTP request'\n\n if not ret['msg'][0].startswith('OK'):\n ret['res'] = False\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
deploy_war
|
python
|
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
|
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L528-L635
|
[
"def extract_war_version(war):\n '''\n Extract the version from the war file name. There does not seem to be a\n standard for encoding the version into the `war file name`_\n\n .. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html\n\n Examples:\n\n .. code-block:: bash\n\n /path/salt-2015.8.6.war -> 2015.8.6\n /path/V6R2013xD5.war -> None\n '''\n basename = os.path.basename(war)\n war_package = os.path.splitext(basename)[0] # remove '.war'\n version = re.findall(\"-([\\\\d.-]+)$\", war_package) # try semver\n return version[0] if version and len(version) == 1 else None # default to none\n",
"def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):\n '''\n A private function used to issue the command to tomcat via the manager\n webapp\n\n cmd\n the command to execute\n\n url\n The URL of the server manager webapp (example:\n http://localhost:8080/manager)\n\n opts\n a dict of arguments\n\n timeout\n timeout for HTTP request\n\n Return value is a dict in the from of::\n\n {\n res: [True|False]\n msg: list of lines we got back from the manager\n }\n '''\n\n ret = {\n 'res': True,\n 'msg': []\n }\n\n # prepare authentication\n auth = _auth(url)\n if auth is False:\n ret['res'] = False\n ret['msg'] = 'missing username and password settings (grain/pillar)'\n return ret\n\n # prepare URL\n if url[-1] != '/':\n url += '/'\n url6 = url\n url += 'text/{0}'.format(cmd)\n url6 += '{0}'.format(cmd)\n if opts:\n url += '?{0}'.format(_urlencode(opts))\n url6 += '?{0}'.format(_urlencode(opts))\n\n # Make the HTTP request\n _install_opener(auth)\n\n try:\n # Trying tomcat >= 7 url\n ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()\n except Exception:\n try:\n # Trying tomcat6 url\n ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()\n except Exception:\n ret['msg'] = 'Failed to create HTTP request'\n\n if not ret['msg'][0].startswith('OK'):\n ret['res'] = False\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
passwd
|
python
|
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
|
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L638-L663
| null |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
version
|
python
|
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
|
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L667-L684
|
[
"def __catalina_home():\n '''\n Tomcat paths differ depending on packaging\n '''\n locations = ['/usr/share/tomcat*', '/opt/tomcat']\n for location in locations:\n folders = glob.glob(location)\n if folders:\n for catalina_home in folders:\n if os.path.isdir(catalina_home + \"/bin\"):\n return catalina_home\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
fullversion
|
python
|
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
|
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L687-L706
|
[
"def __catalina_home():\n '''\n Tomcat paths differ depending on packaging\n '''\n locations = ['/usr/share/tomcat*', '/opt/tomcat']\n for location in locations:\n folders = glob.glob(location)\n if folders:\n for catalina_home in folders:\n if os.path.isdir(catalina_home + \"/bin\"):\n return catalina_home\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/modules/tomcat.py
|
signal
|
python
|
def signal(signal=None):
'''
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
'''
valid_signals = {'forcestop': 'stop -force',
'securestart': 'start -security',
'start': 'start',
'stop': 'stop'}
if signal not in valid_signals:
return
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home(), valid_signals[signal]
)
__salt__['cmd.run'](cmd)
|
Signals catalina to start, stop, securestart, forcestop.
CLI Example:
.. code-block:: bash
salt '*' tomcat.signal start
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tomcat.py#L709-L730
|
[
"def __catalina_home():\n '''\n Tomcat paths differ depending on packaging\n '''\n locations = ['/usr/share/tomcat*', '/opt/tomcat']\n for location in locations:\n folders = glob.glob(location)\n if folders:\n for catalina_home in folders:\n if os.path.isdir(catalina_home + \"/bin\"):\n return catalina_home\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Tomcat
This module uses the manager webapp to manage Apache tomcat webapps.
If the manager webapp is not configured some of the functions won't work.
:configuration:
- Java bin path should be in default path
- If ipv6 is enabled make sure you permit manager access to ipv6 interface
"0:0:0:0:0:0:0:1"
- If you are using tomcat.tar.gz it has to be installed or symlinked under
``/opt``, preferably using name tomcat
- "tomcat.signal start/stop" works but it does not use the startup scripts
The following grains/pillar should be set:
.. code-block:: yaml
tomcat-manager:
user: <username>
passwd: <password>
or the old format:
.. code-block:: yaml
tomcat-manager.user: <username>
tomcat-manager.passwd: <password>
Also configure a user in the conf/tomcat-users.xml file:
.. code-block:: xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<user username="tomcat" password="tomcat" roles="manager-script"/>
</tomcat-users>
.. note::
- More information about tomcat manager:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- if you use only this module for deployments you've might want to strict
access to the manager only from localhost for more info:
http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access
- Tested on:
JVM Vendor:
Sun Microsystems Inc.
JVM Version:
1.6.0_43-b01
OS Architecture:
amd64
OS Name:
Linux
OS Version:
2.6.32-358.el6.x86_64
Tomcat Version:
Apache Tomcat/7.0.37
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import glob
import hashlib
import tempfile
import logging
# Import 3rd-party libs
# pylint: disable=no-name-in-module,import-error
from salt.ext.six import string_types as _string_types
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext.six.moves.urllib.request import (
urlopen as _urlopen,
HTTPBasicAuthHandler as _HTTPBasicAuthHandler,
HTTPDigestAuthHandler as _HTTPDigestAuthHandler,
build_opener as _build_opener,
install_opener as _install_opener
)
# pylint: enable=no-name-in-module,import-error
# Import Salt libs
import salt.utils.data
log = logging.getLogger(__name__)
__func_alias__ = {
'reload_': 'reload'
}
# Support old-style grains/pillar
# config as well as new.
__valid_configs = {
'user': [
'tomcat-manager.user',
'tomcat-manager:user'
],
'passwd': [
'tomcat-manager.passwd',
'tomcat-manager:passwd'
]
}
def __virtual__():
'''
Only load tomcat if it is installed or if grains/pillar config exists
'''
if __catalina_home() or _auth('dummy'):
return 'tomcat'
return (False,
'Tomcat execution module not loaded: neither Tomcat installed locally nor tomcat-manager credentials set in grains/pillar/config.')
def __catalina_home():
'''
Tomcat paths differ depending on packaging
'''
locations = ['/usr/share/tomcat*', '/opt/tomcat']
for location in locations:
folders = glob.glob(location)
if folders:
for catalina_home in folders:
if os.path.isdir(catalina_home + "/bin"):
return catalina_home
return False
def _get_credentials():
'''
Get the username and password from opts, grains, or pillar
'''
ret = {
'user': False,
'passwd': False
}
# Loop through opts, grains, and pillar
# Return the first acceptable configuration found
for item in ret:
for struct in [__opts__, __grains__, __pillar__]:
# Look for the config key
# Support old-style config format and new
for config_key in __valid_configs[item]:
value = salt.utils.data.traverse_dict_and_list(
struct,
config_key,
None)
if value:
ret[item] = value
break
return ret['user'], ret['passwd']
def _auth(uri):
'''
returns a authentication handler.
Get user & password from grains, if are not set default to
modules.config.option
If user & pass are missing return False
'''
user, password = _get_credentials()
if user is False or password is False:
return False
basic = _HTTPBasicAuthHandler()
basic.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm='Tomcat Manager Application', uri=uri,
user=user, passwd=password)
return _build_opener(basic, digest)
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/path/V6R2013xD5.war -> None
'''
basename = os.path.basename(war)
war_package = os.path.splitext(basename)[0] # remove '.war'
version = re.findall("-([\\d.-]+)$", war_package) # try semver
return version[0] if version and len(version) == 1 else None # default to none
def _wget(cmd, opts=None, url='http://localhost:8080/manager', timeout=180):
'''
A private function used to issue the command to tomcat via the manager
webapp
cmd
the command to execute
url
The URL of the server manager webapp (example:
http://localhost:8080/manager)
opts
a dict of arguments
timeout
timeout for HTTP request
Return value is a dict in the from of::
{
res: [True|False]
msg: list of lines we got back from the manager
}
'''
ret = {
'res': True,
'msg': []
}
# prepare authentication
auth = _auth(url)
if auth is False:
ret['res'] = False
ret['msg'] = 'missing username and password settings (grain/pillar)'
return ret
# prepare URL
if url[-1] != '/':
url += '/'
url6 = url
url += 'text/{0}'.format(cmd)
url6 += '{0}'.format(cmd)
if opts:
url += '?{0}'.format(_urlencode(opts))
url6 += '?{0}'.format(_urlencode(opts))
# Make the HTTP request
_install_opener(auth)
try:
# Trying tomcat >= 7 url
ret['msg'] = _urlopen(url, timeout=timeout).read().splitlines()
except Exception:
try:
# Trying tomcat6 url
ret['msg'] = _urlopen(url6, timeout=timeout).read().splitlines()
except Exception:
ret['msg'] = 'Failed to create HTTP request'
if not ret['msg'][0].startswith('OK'):
ret['res'] = False
return ret
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, timeout=timeout)['msg'])
except Exception:
return 'FAIL - No context exists for path {0}'.format(app)
# Functions
def leaks(url='http://localhost:8080/manager', timeout=180):
'''
Find memory leaks in tomcat
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.leaks
'''
return _wget('findleaks', {'statusLine': 'true'},
url, timeout=timeout)['msg']
def status(url='http://localhost:8080/manager', timeout=180):
'''
Used to test if the tomcat manager is up
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status
salt '*' tomcat.status http://localhost:8080/manager
'''
return _wget('list', {}, url, timeout=timeout)['res']
def ls(url='http://localhost:8080/manager', timeout=180):
'''
list all the deployed webapps
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.ls
salt '*' tomcat.ls http://localhost:8080/manager
'''
ret = {}
data = _wget('list', '', url, timeout=timeout)
if data['res'] is False:
return {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0]] = {
'mode': tmp[1],
'sessions': tmp[2],
'fullname': tmp[3],
'version': '',
}
sliced = tmp[3].split('##')
if len(sliced) > 1:
ret[tmp[0]]['version'] = sliced[1]
return ret
def stop(app, url='http://localhost:8080/manager', timeout=180):
'''
Stop the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.stop /jenkins
salt '*' tomcat.stop /jenkins http://localhost:8080/manager
'''
return _simple_cmd('stop', app, url, timeout=timeout)
def start(app, url='http://localhost:8080/manager', timeout=180):
'''
Start the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.start /jenkins
salt '*' tomcat.start /jenkins http://localhost:8080/manager
'''
return _simple_cmd('start', app, url, timeout=timeout)
def reload_(app, url='http://localhost:8080/manager', timeout=180):
'''
Reload the webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.reload /jenkins
salt '*' tomcat.reload /jenkins http://localhost:8080/manager
'''
return _simple_cmd('reload', app, url, timeout=timeout)
def sessions(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp sessions
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.sessions /jenkins
salt '*' tomcat.sessions /jenkins http://localhost:8080/manager
'''
return _simple_cmd('sessions', app, url, timeout=timeout)
def status_webapp(app, url='http://localhost:8080/manager', timeout=180):
'''
return the status of the webapp (stopped | running | missing)
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.status_webapp /jenkins
salt '*' tomcat.status_webapp /jenkins http://localhost:8080/manager
'''
webapps = ls(url, timeout=timeout)
for i in webapps:
if i == app:
return webapps[i]['mode']
return 'missing'
def serverinfo(url='http://localhost:8080/manager', timeout=180):
'''
return details about the server
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.serverinfo
salt '*' tomcat.serverinfo http://localhost:8080/manager
'''
data = _wget('serverinfo', {}, url, timeout=timeout)
if data['res'] is False:
return {'error': data['msg']}
ret = {}
data['msg'].pop(0)
for line in data['msg']:
tmp = line.split(':')
ret[tmp[0].strip()] = tmp[1].strip()
return ret
def undeploy(app, url='http://localhost:8080/manager', timeout=180):
'''
Undeploy a webapp
app
the webapp context path
url : http://localhost:8080/manager
the URL of the server manager webapp
timeout : 180
timeout for HTTP request
CLI Examples:
.. code-block:: bash
salt '*' tomcat.undeploy /jenkins
salt '*' tomcat.undeploy /jenkins http://localhost:8080/manager
'''
return _simple_cmd('undeploy', app, url, timeout=timeout)
def deploy_war(war,
context,
force='no',
url='http://localhost:8080/manager',
saltenv='base',
timeout=180,
temp_war_location=None,
version=True):
'''
Deploy a WAR file
war
absolute path to WAR file (should be accessible by the user running
tomcat) or a path supported by the salt.modules.cp.get_file function
context
the context path to deploy
force : False
set True to deploy the webapp even one is deployed in the context
url : http://localhost:8080/manager
the URL of the server manager webapp
saltenv : base
the environment for WAR file in used by salt.modules.cp.get_url
function
timeout : 180
timeout for HTTP request
temp_war_location : None
use another location to temporarily copy to war file
by default the system's temp directory is used
version : ''
Specify the war version. If this argument is provided, it overrides
the version encoded in the war file name, if one is present.
Examples:
.. code-block:: bash
salt '*' tomcat.deploy_war salt://salt-2015.8.6.war version=2015.08.r6
.. versionadded:: 2015.8.6
CLI Examples:
cp module
.. code-block:: bash
salt '*' tomcat.deploy_war salt://application.war /api
salt '*' tomcat.deploy_war salt://application.war /api no
salt '*' tomcat.deploy_war salt://application.war /api yes http://localhost:8080/manager
minion local file system
.. code-block:: bash
salt '*' tomcat.deploy_war /tmp/application.war /api
salt '*' tomcat.deploy_war /tmp/application.war /api no
salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager
'''
# Decide the location to copy the war for the deployment
tfile = 'salt.{0}'.format(os.path.basename(war))
if temp_war_location is not None:
if not os.path.isdir(temp_war_location):
return 'Error - "{0}" is not a directory'.format(temp_war_location)
tfile = os.path.join(temp_war_location, tfile)
else:
tfile = os.path.join(tempfile.gettempdir(), tfile)
# Copy file name if needed
cache = False
if not os.path.isfile(war):
cache = True
cached = __salt__['cp.get_url'](war, tfile, saltenv)
if not cached:
return 'FAIL - could not cache the WAR file'
try:
__salt__['file.set_mode'](cached, '0644')
except KeyError:
pass
else:
tfile = war
# Prepare options
opts = {
'war': 'file:{0}'.format(tfile),
'path': context,
}
# If parallel versions are desired or not disabled
if version:
# Set it to defined version or attempt extract
version = extract_war_version(war) if version is True else version
if isinstance(version, _string_types):
# Only pass version to Tomcat if not undefined
opts['version'] = version
if force == 'yes':
opts['update'] = 'true'
# Deploy
deployed = _wget('deploy', opts, url, timeout=timeout)
res = '\n'.join(deployed['msg'])
# Cleanup
if cache:
__salt__['file.remove'](tfile)
return res
def passwd(passwd,
user='',
alg='sha1',
realm=None):
'''
This function replaces the $CATALINA_HOME/bin/digest.sh script
convert a clear-text password to the $CATALINA_BASE/conf/tomcat-users.xml
format
CLI Examples:
.. code-block:: bash
salt '*' tomcat.passwd secret
salt '*' tomcat.passwd secret tomcat sha1
salt '*' tomcat.passwd secret tomcat sha1 'Protected Realm'
'''
# Shouldn't it be SHA265 instead of SHA1?
digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None
if digest:
if realm:
digest.update('{0}:{1}:{2}'.format(user, realm, passwd, ))
else:
digest.update(passwd)
return digest and digest.hexdigest() or False
# Non-Manager functions
def version():
'''
Return server version from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.version
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if 'Server version' in line:
comps = line.split(': ')
return comps[1]
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if ': ' in line:
comps = line.split(': ')
ret[comps[0]] = comps[1].lstrip()
return ret
if __name__ == '__main__':
'''
Allow testing from the CLI
''' # pylint: disable=W0105
__opts__ = {}
__grains__ = {}
__pillar__ = {
'tomcat-manager.user': 'foobar',
'tomcat-manager.passwd': 'barfoo1!',
}
old_format_creds = _get_credentials()
__pillar__ = {
'tomcat-manager': {
'user': 'foobar',
'passwd': 'barfoo1!'
}
}
new_format_creds = _get_credentials()
if old_format_creds == new_format_creds:
log.info('Config backwards compatible')
else:
log.ifno('Config not backwards compatible')
|
saltstack/salt
|
salt/returners/appoptics_return.py
|
_get_options
|
python
|
def _get_options(ret=None):
'''
Get the appoptics options from salt.
'''
attrs = {
'api_token': 'api_token',
'api_url': 'api_url',
'tags': 'tags',
'sls_states': 'sls_states'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
_options['api_url'] = _options.get('api_url', 'api.appoptics.com')
_options['sls_states'] = _options.get('sls_states', [])
_options['tags'] = _options.get('tags', {
'host_hostname_alias': __salt__['grains.get']('id')
})
log.debug('Retrieved appoptics options: %s', _options)
return _options
|
Get the appoptics options from salt.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/appoptics_return.py#L98-L123
|
[
"def get_returner_options(virtualname=None,\n ret=None,\n attrs=None,\n **kwargs):\n '''\n Get the returner options from salt.\n\n :param str virtualname: The returner virtualname (as returned\n by __virtual__()\n :param ret: result of the module that ran. dict-like object\n\n May contain a `ret_config` key pointing to a string\n If a `ret_config` is specified, config options are read from::\n\n value.virtualname.option\n\n If not, config options are read from::\n\n value.virtualname.option\n\n :param attrs: options the returner wants to read\n :param __opts__: Optional dict-like object that contains a fallback config\n in case the param `__salt__` is not supplied.\n\n Defaults to empty dict.\n :param __salt__: Optional dict-like object that exposes the salt API.\n\n Defaults to empty dict.\n\n a) if __salt__ contains a 'config.option' configuration options,\n we infer the returner is being called from a state or module run ->\n config is a copy of the `config.option` function\n\n b) if __salt__ was not available, we infer that the returner is being\n called from the Salt scheduler, so we look for the\n configuration options in the param `__opts__`\n -> cfg is a copy for the __opts__ dictionary\n :param str profile_attr: Optional.\n\n If supplied, an overriding config profile is read from\n the corresponding key of `__salt__`.\n\n :param dict profile_attrs: Optional\n\n .. fixme:: only keys are read\n\n For each key in profile_attr, a value is read in the are\n used to fetch a value pointed by 'virtualname.%key' in\n the dict found thanks to the param `profile_attr`\n '''\n\n ret_config = _fetch_ret_config(ret)\n\n attrs = attrs or {}\n profile_attr = kwargs.get('profile_attr', None)\n profile_attrs = kwargs.get('profile_attrs', None)\n defaults = kwargs.get('defaults', None)\n __salt__ = kwargs.get('__salt__', {})\n __opts__ = kwargs.get('__opts__', {})\n\n # select the config source\n cfg = __salt__.get('config.option', __opts__)\n\n # browse the config for relevant options, store them in a dict\n _options = dict(\n _options_browser(\n cfg,\n ret_config,\n defaults,\n virtualname,\n attrs,\n )\n )\n\n # override some values with relevant profile options\n _options.update(\n _fetch_profile_opts(\n cfg,\n virtualname,\n __salt__,\n _options,\n profile_attr,\n profile_attrs\n )\n )\n\n # override some values with relevant options from\n # keyword arguments passed via return_kwargs\n if ret and 'ret_kwargs' in ret:\n _options.update(ret['ret_kwargs'])\n\n return _options\n"
] |
# -*- coding: utf-8 -*-
'''Salt returner to return highstate stats to AppOptics Metrics
To enable this returner the minion will need the AppOptics Metrics
client importable on the Python path and the following
values configured in the minion or master config.
The AppOptics python client can be found at:
https://github.com/appoptics/python-appoptics-metrics
.. code-block:: yaml
appoptics.api_token: abc12345def
An example configuration that returns the total number of successes
and failures for your salt highstate runs (the default) would look
like this:
.. code-block:: yaml
return: appoptics
appoptics.api_token: <token string here>
The returner publishes the following metrics to AppOptics:
- saltstack.failed
- saltstack.passed
- saltstack.retcode
- saltstack.runtime
- saltstack.total
You can add a tags section to specify which tags should be attached to
all metrics created by the returner.
.. code-block:: yaml
appoptics.tags:
host_hostname_alias: <the minion ID - matches @host>
tier: <the tier/etc. of this node>
cluster: <the cluster name, etc.>
If no tags are explicitly configured, then the tag key ``host_hostname_alias``
will be set, with the minion's ``id`` grain being the value.
In addition to the requested tags, for a highstate run each of these
will be tagged with the ``key:value`` of ``state_type: highstate``.
In order to return metrics for ``state.sls`` runs (distinct from highstates), you can
specify a list of state names to the key ``appoptics.sls_states`` like so:
.. code-block:: yaml
appoptics.sls_states:
- role_salt_master.netapi
- role_redis.config
- role_smarty.dummy
This will report success and failure counts on runs of the
``role_salt_master.netapi``, ``role_redis.config``, and
``role_smarty.dummy`` states in addition to highstates.
This will report the same metrics as above, but for these runs the
metrics will be tagged with ``state_type: sls`` and ``state_name`` set to
the name of the state that was invoked, e.g. ``role_salt_master.netapi``.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
# Import third party libs
try:
import appoptics_metrics
HAS_APPOPTICS = True
except ImportError:
HAS_APPOPTICS = False
# Define the module's Virtual Name
__virtualname__ = 'appoptics'
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_APPOPTICS:
return False, 'Could not import appoptics_metrics module; ' \
'appoptics-metrics python client is not installed.'
return __virtualname__
def _get_appoptics(options):
'''
Return an appoptics connection object.
'''
conn = appoptics_metrics.connect(
options.get('api_token'),
sanitizer=appoptics_metrics.sanitize_metric_name,
hostname=options.get('api_url'))
log.info("Connected to appoptics.")
return conn
def _calculate_runtimes(states):
results = {
'runtime': 0.00,
'num_failed_states': 0,
'num_passed_states': 0
}
for state, resultset in states.items():
if isinstance(resultset, dict) and 'duration' in resultset:
# Count the pass vs failures
if resultset['result']:
results['num_passed_states'] += 1
else:
results['num_failed_states'] += 1
# Count durations
results['runtime'] += resultset['duration']
log.debug('Parsed state metrics: %s', results)
return results
def _state_metrics(ret, options, tags):
# Calculate the runtimes and number of failed states.
stats = _calculate_runtimes(ret['return'])
log.debug('Batching Metric retcode with %s', ret['retcode'])
appoptics_conn = _get_appoptics(options)
q = appoptics_conn.new_queue(tags=tags)
q.add('saltstack.retcode', ret['retcode'])
log.debug('Batching Metric num_failed_jobs with %s', stats['num_failed_states'])
q.add('saltstack.failed', stats['num_failed_states'])
log.debug('Batching Metric num_passed_states with %s',
stats['num_passed_states'])
q.add('saltstack.passed', stats['num_passed_states'])
log.debug('Batching Metric runtime with %s', stats['runtime'])
q.add('saltstack.runtime', stats['runtime'])
log.debug('Batching with Metric total states %s',
(stats['num_failed_states'] + stats['num_passed_states']))
q.add('saltstack.highstate.total_states',
(stats['num_failed_states'] + stats['num_passed_states']))
log.info('Sending metrics to appoptics.')
q.submit()
def returner(ret):
'''
Parse the return data and return metrics to AppOptics.
For each state that's provided in the configuration, return tagged metrics for
the result of that state if it's present.
'''
options = _get_options(ret)
states_to_report = ['state.highstate']
if options.get('sls_states'):
states_to_report.append('state.sls')
if ret['fun'] in states_to_report:
tags = options.get('tags', {}).copy()
tags['state_type'] = ret['fun']
log.info("Tags for this run are %s", tags)
matched_states = set(ret['fun_args']).intersection(
set(options.get('sls_states', [])))
# What can I do if a run has multiple states that match?
# In the mean time, find one matching state name and use it.
if matched_states:
tags['state_name'] = sorted(matched_states)[0]
log.debug('Found returned data from %s.', tags['state_name'])
_state_metrics(ret, options, tags)
|
saltstack/salt
|
salt/returners/appoptics_return.py
|
_get_appoptics
|
python
|
def _get_appoptics(options):
'''
Return an appoptics connection object.
'''
conn = appoptics_metrics.connect(
options.get('api_token'),
sanitizer=appoptics_metrics.sanitize_metric_name,
hostname=options.get('api_url'))
log.info("Connected to appoptics.")
return conn
|
Return an appoptics connection object.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/appoptics_return.py#L126-L135
| null |
# -*- coding: utf-8 -*-
'''Salt returner to return highstate stats to AppOptics Metrics
To enable this returner the minion will need the AppOptics Metrics
client importable on the Python path and the following
values configured in the minion or master config.
The AppOptics python client can be found at:
https://github.com/appoptics/python-appoptics-metrics
.. code-block:: yaml
appoptics.api_token: abc12345def
An example configuration that returns the total number of successes
and failures for your salt highstate runs (the default) would look
like this:
.. code-block:: yaml
return: appoptics
appoptics.api_token: <token string here>
The returner publishes the following metrics to AppOptics:
- saltstack.failed
- saltstack.passed
- saltstack.retcode
- saltstack.runtime
- saltstack.total
You can add a tags section to specify which tags should be attached to
all metrics created by the returner.
.. code-block:: yaml
appoptics.tags:
host_hostname_alias: <the minion ID - matches @host>
tier: <the tier/etc. of this node>
cluster: <the cluster name, etc.>
If no tags are explicitly configured, then the tag key ``host_hostname_alias``
will be set, with the minion's ``id`` grain being the value.
In addition to the requested tags, for a highstate run each of these
will be tagged with the ``key:value`` of ``state_type: highstate``.
In order to return metrics for ``state.sls`` runs (distinct from highstates), you can
specify a list of state names to the key ``appoptics.sls_states`` like so:
.. code-block:: yaml
appoptics.sls_states:
- role_salt_master.netapi
- role_redis.config
- role_smarty.dummy
This will report success and failure counts on runs of the
``role_salt_master.netapi``, ``role_redis.config``, and
``role_smarty.dummy`` states in addition to highstates.
This will report the same metrics as above, but for these runs the
metrics will be tagged with ``state_type: sls`` and ``state_name`` set to
the name of the state that was invoked, e.g. ``role_salt_master.netapi``.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
# Import third party libs
try:
import appoptics_metrics
HAS_APPOPTICS = True
except ImportError:
HAS_APPOPTICS = False
# Define the module's Virtual Name
__virtualname__ = 'appoptics'
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_APPOPTICS:
return False, 'Could not import appoptics_metrics module; ' \
'appoptics-metrics python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the appoptics options from salt.
'''
attrs = {
'api_token': 'api_token',
'api_url': 'api_url',
'tags': 'tags',
'sls_states': 'sls_states'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
_options['api_url'] = _options.get('api_url', 'api.appoptics.com')
_options['sls_states'] = _options.get('sls_states', [])
_options['tags'] = _options.get('tags', {
'host_hostname_alias': __salt__['grains.get']('id')
})
log.debug('Retrieved appoptics options: %s', _options)
return _options
def _calculate_runtimes(states):
results = {
'runtime': 0.00,
'num_failed_states': 0,
'num_passed_states': 0
}
for state, resultset in states.items():
if isinstance(resultset, dict) and 'duration' in resultset:
# Count the pass vs failures
if resultset['result']:
results['num_passed_states'] += 1
else:
results['num_failed_states'] += 1
# Count durations
results['runtime'] += resultset['duration']
log.debug('Parsed state metrics: %s', results)
return results
def _state_metrics(ret, options, tags):
# Calculate the runtimes and number of failed states.
stats = _calculate_runtimes(ret['return'])
log.debug('Batching Metric retcode with %s', ret['retcode'])
appoptics_conn = _get_appoptics(options)
q = appoptics_conn.new_queue(tags=tags)
q.add('saltstack.retcode', ret['retcode'])
log.debug('Batching Metric num_failed_jobs with %s', stats['num_failed_states'])
q.add('saltstack.failed', stats['num_failed_states'])
log.debug('Batching Metric num_passed_states with %s',
stats['num_passed_states'])
q.add('saltstack.passed', stats['num_passed_states'])
log.debug('Batching Metric runtime with %s', stats['runtime'])
q.add('saltstack.runtime', stats['runtime'])
log.debug('Batching with Metric total states %s',
(stats['num_failed_states'] + stats['num_passed_states']))
q.add('saltstack.highstate.total_states',
(stats['num_failed_states'] + stats['num_passed_states']))
log.info('Sending metrics to appoptics.')
q.submit()
def returner(ret):
'''
Parse the return data and return metrics to AppOptics.
For each state that's provided in the configuration, return tagged metrics for
the result of that state if it's present.
'''
options = _get_options(ret)
states_to_report = ['state.highstate']
if options.get('sls_states'):
states_to_report.append('state.sls')
if ret['fun'] in states_to_report:
tags = options.get('tags', {}).copy()
tags['state_type'] = ret['fun']
log.info("Tags for this run are %s", tags)
matched_states = set(ret['fun_args']).intersection(
set(options.get('sls_states', [])))
# What can I do if a run has multiple states that match?
# In the mean time, find one matching state name and use it.
if matched_states:
tags['state_name'] = sorted(matched_states)[0]
log.debug('Found returned data from %s.', tags['state_name'])
_state_metrics(ret, options, tags)
|
saltstack/salt
|
salt/returners/appoptics_return.py
|
returner
|
python
|
def returner(ret):
'''
Parse the return data and return metrics to AppOptics.
For each state that's provided in the configuration, return tagged metrics for
the result of that state if it's present.
'''
options = _get_options(ret)
states_to_report = ['state.highstate']
if options.get('sls_states'):
states_to_report.append('state.sls')
if ret['fun'] in states_to_report:
tags = options.get('tags', {}).copy()
tags['state_type'] = ret['fun']
log.info("Tags for this run are %s", tags)
matched_states = set(ret['fun_args']).intersection(
set(options.get('sls_states', [])))
# What can I do if a run has multiple states that match?
# In the mean time, find one matching state name and use it.
if matched_states:
tags['state_name'] = sorted(matched_states)[0]
log.debug('Found returned data from %s.', tags['state_name'])
_state_metrics(ret, options, tags)
|
Parse the return data and return metrics to AppOptics.
For each state that's provided in the configuration, return tagged metrics for
the result of that state if it's present.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/appoptics_return.py#L186-L209
|
[
"def _get_options(ret=None):\n '''\n Get the appoptics options from salt.\n '''\n attrs = {\n 'api_token': 'api_token',\n 'api_url': 'api_url',\n 'tags': 'tags',\n 'sls_states': 'sls_states'\n }\n\n _options = salt.returners.get_returner_options(\n __virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n\n _options['api_url'] = _options.get('api_url', 'api.appoptics.com')\n _options['sls_states'] = _options.get('sls_states', [])\n _options['tags'] = _options.get('tags', {\n 'host_hostname_alias': __salt__['grains.get']('id')\n })\n\n log.debug('Retrieved appoptics options: %s', _options)\n return _options\n",
"def _state_metrics(ret, options, tags):\n # Calculate the runtimes and number of failed states.\n stats = _calculate_runtimes(ret['return'])\n log.debug('Batching Metric retcode with %s', ret['retcode'])\n appoptics_conn = _get_appoptics(options)\n q = appoptics_conn.new_queue(tags=tags)\n\n q.add('saltstack.retcode', ret['retcode'])\n log.debug('Batching Metric num_failed_jobs with %s', stats['num_failed_states'])\n q.add('saltstack.failed', stats['num_failed_states'])\n\n log.debug('Batching Metric num_passed_states with %s',\n stats['num_passed_states'])\n q.add('saltstack.passed', stats['num_passed_states'])\n\n log.debug('Batching Metric runtime with %s', stats['runtime'])\n q.add('saltstack.runtime', stats['runtime'])\n\n log.debug('Batching with Metric total states %s',\n (stats['num_failed_states'] + stats['num_passed_states']))\n q.add('saltstack.highstate.total_states',\n (stats['num_failed_states'] + stats['num_passed_states']))\n log.info('Sending metrics to appoptics.')\n q.submit()\n"
] |
# -*- coding: utf-8 -*-
'''Salt returner to return highstate stats to AppOptics Metrics
To enable this returner the minion will need the AppOptics Metrics
client importable on the Python path and the following
values configured in the minion or master config.
The AppOptics python client can be found at:
https://github.com/appoptics/python-appoptics-metrics
.. code-block:: yaml
appoptics.api_token: abc12345def
An example configuration that returns the total number of successes
and failures for your salt highstate runs (the default) would look
like this:
.. code-block:: yaml
return: appoptics
appoptics.api_token: <token string here>
The returner publishes the following metrics to AppOptics:
- saltstack.failed
- saltstack.passed
- saltstack.retcode
- saltstack.runtime
- saltstack.total
You can add a tags section to specify which tags should be attached to
all metrics created by the returner.
.. code-block:: yaml
appoptics.tags:
host_hostname_alias: <the minion ID - matches @host>
tier: <the tier/etc. of this node>
cluster: <the cluster name, etc.>
If no tags are explicitly configured, then the tag key ``host_hostname_alias``
will be set, with the minion's ``id`` grain being the value.
In addition to the requested tags, for a highstate run each of these
will be tagged with the ``key:value`` of ``state_type: highstate``.
In order to return metrics for ``state.sls`` runs (distinct from highstates), you can
specify a list of state names to the key ``appoptics.sls_states`` like so:
.. code-block:: yaml
appoptics.sls_states:
- role_salt_master.netapi
- role_redis.config
- role_smarty.dummy
This will report success and failure counts on runs of the
``role_salt_master.netapi``, ``role_redis.config``, and
``role_smarty.dummy`` states in addition to highstates.
This will report the same metrics as above, but for these runs the
metrics will be tagged with ``state_type: sls`` and ``state_name`` set to
the name of the state that was invoked, e.g. ``role_salt_master.netapi``.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
import salt.utils.jid
import salt.returners
# Import third party libs
try:
import appoptics_metrics
HAS_APPOPTICS = True
except ImportError:
HAS_APPOPTICS = False
# Define the module's Virtual Name
__virtualname__ = 'appoptics'
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_APPOPTICS:
return False, 'Could not import appoptics_metrics module; ' \
'appoptics-metrics python client is not installed.'
return __virtualname__
def _get_options(ret=None):
'''
Get the appoptics options from salt.
'''
attrs = {
'api_token': 'api_token',
'api_url': 'api_url',
'tags': 'tags',
'sls_states': 'sls_states'
}
_options = salt.returners.get_returner_options(
__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
_options['api_url'] = _options.get('api_url', 'api.appoptics.com')
_options['sls_states'] = _options.get('sls_states', [])
_options['tags'] = _options.get('tags', {
'host_hostname_alias': __salt__['grains.get']('id')
})
log.debug('Retrieved appoptics options: %s', _options)
return _options
def _get_appoptics(options):
'''
Return an appoptics connection object.
'''
conn = appoptics_metrics.connect(
options.get('api_token'),
sanitizer=appoptics_metrics.sanitize_metric_name,
hostname=options.get('api_url'))
log.info("Connected to appoptics.")
return conn
def _calculate_runtimes(states):
results = {
'runtime': 0.00,
'num_failed_states': 0,
'num_passed_states': 0
}
for state, resultset in states.items():
if isinstance(resultset, dict) and 'duration' in resultset:
# Count the pass vs failures
if resultset['result']:
results['num_passed_states'] += 1
else:
results['num_failed_states'] += 1
# Count durations
results['runtime'] += resultset['duration']
log.debug('Parsed state metrics: %s', results)
return results
def _state_metrics(ret, options, tags):
# Calculate the runtimes and number of failed states.
stats = _calculate_runtimes(ret['return'])
log.debug('Batching Metric retcode with %s', ret['retcode'])
appoptics_conn = _get_appoptics(options)
q = appoptics_conn.new_queue(tags=tags)
q.add('saltstack.retcode', ret['retcode'])
log.debug('Batching Metric num_failed_jobs with %s', stats['num_failed_states'])
q.add('saltstack.failed', stats['num_failed_states'])
log.debug('Batching Metric num_passed_states with %s',
stats['num_passed_states'])
q.add('saltstack.passed', stats['num_passed_states'])
log.debug('Batching Metric runtime with %s', stats['runtime'])
q.add('saltstack.runtime', stats['runtime'])
log.debug('Batching with Metric total states %s',
(stats['num_failed_states'] + stats['num_passed_states']))
q.add('saltstack.highstate.total_states',
(stats['num_failed_states'] + stats['num_passed_states']))
log.info('Sending metrics to appoptics.')
q.submit()
|
saltstack/salt
|
salt/states/zabbix_service.py
|
present
|
python
|
def present(host, service_root, trigger_desc, service_name=None, **kwargs):
'''
.. versionadded:: Fluorine
Ensure service exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split by /)
:param service_name: Name of service
:param trigger_desc: Description of trigger in zabbix
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If services on path does not exists they are created.
.. code-block:: yaml
create_service_icmp:
zabbix_service.present:
- host: server-1
- service_root: Server-group/server icmp
- service_name: server-1-icmp
- trigger_desc: is unavailable by ICMP
'''
if not service_name:
service_name = host
changes_service_added = {host: {'old': 'Service {0} does not exist under {1}.'.format(service_name, service_root),
'new': 'Service {0} added under {1}.'.format(service_name, service_root),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if not host_exists:
ret['comment'] = 'Host {0} does not exists.'.format(host)
return ret
host = __salt__['zabbix.host_get'](name=host, **connection_args)[0]
hostid = host['hostid']
trigger = __salt__['zabbix.triggerid_get'](hostid=hostid, trigger_desc=trigger_desc, **kwargs)
if not trigger:
ret['comment'] = 'Trigger with description: "{0}" does not exists for host {1}.'.format(
trigger_desc, host['name'])
return ret
trigger_id = trigger['result']['triggerid']
root_services = service_root.split('/')
root_id = None
if __opts__['test']:
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = None
ret['comment'] = "Service {0} will be added".format(service_name)
ret['changes'] = changes_service_added
return ret
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if service:
ret['result'] = True
ret['comment'] = "Service {0} already exists".format(service_name)
else:
ret['result'] = None
ret['comment'] = "Service {0} will be added".format(service_name)
ret['changes'] = changes_service_added
return ret
root_id = None
# ensure that root services exists
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
service = __salt__['zabbix.service_add'](service_rootid=root_id, service_name=root_s, **kwargs)
root_id = service['serviceids'][0]
else:
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
service = __salt__['zabbix.service_add'](
service_rootid=root_id, service_name=service_name, triggerid=trigger_id, **kwargs)
if service:
ret['comment'] = "Service {0} added {1} {0} {2}".format(service_name, root_id, trigger_id)
ret['changes'] = changes_service_added
ret['result'] = True
else:
ret['comment'] = "Service {0} could not be added".format(service_name)
ret['result'] = False
else:
ret['comment'] = "Service {0} already exists".format(service_name)
ret['result'] = True
return ret
|
.. versionadded:: Fluorine
Ensure service exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split by /)
:param service_name: Name of service
:param trigger_desc: Description of trigger in zabbix
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If services on path does not exists they are created.
.. code-block:: yaml
create_service_icmp:
zabbix_service.present:
- host: server-1
- service_root: Server-group/server icmp
- service_name: server-1-icmp
- trigger_desc: is unavailable by ICMP
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_service.py#L17-L128
| null |
# -*- coding: utf-8 -*-
'''
Management of Zabbix services.
'''
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only make these states available if Zabbix module is available.
'''
return 'zabbix.service_add' in __salt__
def absent(host, service_root, service_name=None, **kwargs):
'''
.. versionadded:: Fluorine
Ensure service does not exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split /)
:param service_name: Name of service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_service_icmp:
zabbix_service.absent:
- host: server-1
- service_root: server-group/server icmp
- service_name: server-1-icmp
'''
if not service_name:
service_name = host
changes_service_deleted = {host: {'old': 'Service {0} exist under {1}.'.format(service_name, service_root),
'new': 'Service {0} deleted under {1}.'.format(service_name, service_root),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if not host_exists:
ret['comment'] = 'Host {0} does not exists.'.format(host)
return ret
root_services = service_root.split('/')
root_id = None
if __opts__['test']:
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = None
ret['comment'] = "Service {0} will be deleted".format(service_name)
ret['changes'] = changes_service_deleted
return ret
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
else:
ret['result'] = None
ret['comment'] = "Service {0} will be deleted".format(service_name)
ret['changes'] = changes_service_deleted
return ret
root_id = None
# ensure that root services exists
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
return ret
else:
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
return ret
else:
service = __salt__['zabbix.service_delete'](service_id=service[0]['serviceid'], **connection_args)
if service:
ret['comment'] = "Service {0} deleted".format(service_name)
ret['changes'] = changes_service_deleted
ret['result'] = True
else:
ret['comment'] = "Service {0} could not be deleted".format(service_name)
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/zabbix_service.py
|
absent
|
python
|
def absent(host, service_root, service_name=None, **kwargs):
'''
.. versionadded:: Fluorine
Ensure service does not exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split /)
:param service_name: Name of service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_service_icmp:
zabbix_service.absent:
- host: server-1
- service_root: server-group/server icmp
- service_name: server-1-icmp
'''
if not service_name:
service_name = host
changes_service_deleted = {host: {'old': 'Service {0} exist under {1}.'.format(service_name, service_root),
'new': 'Service {0} deleted under {1}.'.format(service_name, service_root),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if not host_exists:
ret['comment'] = 'Host {0} does not exists.'.format(host)
return ret
root_services = service_root.split('/')
root_id = None
if __opts__['test']:
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = None
ret['comment'] = "Service {0} will be deleted".format(service_name)
ret['changes'] = changes_service_deleted
return ret
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
else:
ret['result'] = None
ret['comment'] = "Service {0} will be deleted".format(service_name)
ret['changes'] = changes_service_deleted
return ret
root_id = None
# ensure that root services exists
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
return ret
else:
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
ret['result'] = True
ret['comment'] = "Service {0} does not exists".format(service_name)
return ret
else:
service = __salt__['zabbix.service_delete'](service_id=service[0]['serviceid'], **connection_args)
if service:
ret['comment'] = "Service {0} deleted".format(service_name)
ret['changes'] = changes_service_deleted
ret['result'] = True
else:
ret['comment'] = "Service {0} could not be deleted".format(service_name)
ret['result'] = False
return ret
|
.. versionadded:: Fluorine
Ensure service does not exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split /)
:param service_name: Name of service
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_service_icmp:
zabbix_service.absent:
- host: server-1
- service_root: server-group/server icmp
- service_name: server-1-icmp
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_service.py#L131-L225
| null |
# -*- coding: utf-8 -*-
'''
Management of Zabbix services.
'''
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only make these states available if Zabbix module is available.
'''
return 'zabbix.service_add' in __salt__
def present(host, service_root, trigger_desc, service_name=None, **kwargs):
'''
.. versionadded:: Fluorine
Ensure service exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split by /)
:param service_name: Name of service
:param trigger_desc: Description of trigger in zabbix
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If services on path does not exists they are created.
.. code-block:: yaml
create_service_icmp:
zabbix_service.present:
- host: server-1
- service_root: Server-group/server icmp
- service_name: server-1-icmp
- trigger_desc: is unavailable by ICMP
'''
if not service_name:
service_name = host
changes_service_added = {host: {'old': 'Service {0} does not exist under {1}.'.format(service_name, service_root),
'new': 'Service {0} added under {1}.'.format(service_name, service_root),
}
}
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': host, 'changes': {}, 'result': False, 'comment': ''}
host_exists = __salt__['zabbix.host_exists'](host, **connection_args)
if not host_exists:
ret['comment'] = 'Host {0} does not exists.'.format(host)
return ret
host = __salt__['zabbix.host_get'](name=host, **connection_args)[0]
hostid = host['hostid']
trigger = __salt__['zabbix.triggerid_get'](hostid=hostid, trigger_desc=trigger_desc, **kwargs)
if not trigger:
ret['comment'] = 'Trigger with description: "{0}" does not exists for host {1}.'.format(
trigger_desc, host['name'])
return ret
trigger_id = trigger['result']['triggerid']
root_services = service_root.split('/')
root_id = None
if __opts__['test']:
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
ret['result'] = None
ret['comment'] = "Service {0} will be added".format(service_name)
ret['changes'] = changes_service_added
return ret
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if service:
ret['result'] = True
ret['comment'] = "Service {0} already exists".format(service_name)
else:
ret['result'] = None
ret['comment'] = "Service {0} will be added".format(service_name)
ret['changes'] = changes_service_added
return ret
root_id = None
# ensure that root services exists
for root_s in root_services:
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=root_s, **kwargs)
if not service:
service = __salt__['zabbix.service_add'](service_rootid=root_id, service_name=root_s, **kwargs)
root_id = service['serviceids'][0]
else:
root_id = service[0]['serviceid']
service = __salt__['zabbix.service_get'](service_rootid=root_id, service_name=service_name, **kwargs)
if not service:
service = __salt__['zabbix.service_add'](
service_rootid=root_id, service_name=service_name, triggerid=trigger_id, **kwargs)
if service:
ret['comment'] = "Service {0} added {1} {0} {2}".format(service_name, root_id, trigger_id)
ret['changes'] = changes_service_added
ret['result'] = True
else:
ret['comment'] = "Service {0} could not be added".format(service_name)
ret['result'] = False
else:
ret['comment'] = "Service {0} already exists".format(service_name)
ret['result'] = True
return ret
|
saltstack/salt
|
salt/cli/support/intfunc.py
|
filetree
|
python
|
def filetree(collector, *paths):
'''
Add all files in the tree. If the "path" is a file,
only that file will be added.
:param path: File or directory
:return:
'''
_paths = []
# Unglob
for path in paths:
_paths += glob.glob(path)
for path in set(_paths):
if not path:
out.error('Path not defined', ident=2)
elif not os.path.exists(path):
out.warning('Path {} does not exists'.format(path))
else:
# The filehandler needs to be explicitly passed here, so PyLint needs to accept that.
# pylint: disable=W8470
if os.path.isfile(path):
filename = os.path.basename(path)
try:
file_ref = salt.utils.files.fopen(path) # pylint: disable=W
out.put('Add {}'.format(filename), indent=2)
collector.add(filename)
collector.link(title=path, path=file_ref)
except Exception as err:
out.error(err, ident=4)
# pylint: enable=W8470
else:
try:
for fname in os.listdir(path):
fname = os.path.join(path, fname)
filetree(collector, [fname])
except Exception as err:
out.error(err, ident=4)
|
Add all files in the tree. If the "path" is a file,
only that file will be added.
:param path: File or directory
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/intfunc.py#L17-L53
|
[
"def warning(self, message, ident=0):\n '''\n Write a warning message to the CLI.\n\n :param message:\n :param ident:\n :return:\n '''\n self.__colored_output('Warning', message, 'YELLOW', 'LIGHT_YELLOW', ident=ident)\n",
"def error(self, message, ident=0):\n '''\n Write an error message to the CLI.\n\n :param message:\n :param ident\n :return:\n '''\n self.__colored_output('Error', message, 'RED', 'LIGHT_RED', ident=ident)\n"
] |
# coding=utf-8
'''
Internal functions.
'''
# Maybe this needs to be a modules in a future?
from __future__ import absolute_import, print_function, unicode_literals
import os
import glob
from salt.cli.support.console import MessagesOutput
import salt.utils.files
out = MessagesOutput()
|
saltstack/salt
|
salt/modules/win_powercfg.py
|
_get_powercfg_minute_values
|
python
|
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
out = s
break
else:
out = split[0]
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60}
|
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L44-L69
|
[
"def _get_current_scheme():\n cmd = 'powercfg /getactivescheme'\n out = __salt__['cmd.run'](cmd, python_shell=False)\n matches = re.search(r'GUID: (.*) \\(', out)\n return matches.groups()[0].strip()\n"
] |
# -*- coding: utf-8 -*-
'''
This module allows you to control the power settings of a windows minion via
powercfg.
.. versionadded:: 2015.8.0
.. code-block:: bash
# Set monitor to never turn off on Battery power
salt '*' powercfg.set_monitor_timeout 0 power=dc
# Set disk timeout to 120 minutes on AC power
salt '*' powercfg.set_disk_timeout 120 power=ac
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import re
import logging
# Import Salt Libs
import salt.utils.platform
log = logging.getLogger(__name__)
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _get_current_scheme():
cmd = 'powercfg /getactivescheme'
out = __salt__['cmd.run'](cmd, python_shell=False)
matches = re.search(r'GUID: (.*) \(', out)
return matches.groups()[0].strip()
def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the AC/DC values of a setting with the given power for the given scheme
'''
if scheme is None:
scheme = _get_current_scheme()
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout)
def get_monitor_timeout(scheme=None):
'''
Get the current monitor timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_monitor_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_VIDEO',
subguid='VIDEOIDLE',
safe_name='Turn off display after')
def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout)
def get_disk_timeout(scheme=None):
'''
Get the current disk timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_disk_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_DISK',
subguid='DISKIDLE',
safe_name='Turn off hard disk after')
def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout)
def get_standby_timeout(scheme=None):
'''
Get the current standby timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_standby_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='STANDBYIDLE',
safe_name='Sleep after')
def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout)
def get_hibernate_timeout(scheme=None):
'''
Get the current hibernate timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_hibernate_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='HIBERNATEIDLE',
safe_name='Hibernate after')
|
saltstack/salt
|
salt/modules/win_powercfg.py
|
_set_powercfg_value
|
python
|
def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the AC/DC values of a setting with the given power for the given scheme
'''
if scheme is None:
scheme = _get_current_scheme()
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
|
Sets the AC/DC values of a setting with the given power for the given scheme
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L72-L81
|
[
"def _get_current_scheme():\n cmd = 'powercfg /getactivescheme'\n out = __salt__['cmd.run'](cmd, python_shell=False)\n matches = re.search(r'GUID: (.*) \\(', out)\n return matches.groups()[0].strip()\n"
] |
# -*- coding: utf-8 -*-
'''
This module allows you to control the power settings of a windows minion via
powercfg.
.. versionadded:: 2015.8.0
.. code-block:: bash
# Set monitor to never turn off on Battery power
salt '*' powercfg.set_monitor_timeout 0 power=dc
# Set disk timeout to 120 minutes on AC power
salt '*' powercfg.set_disk_timeout 120 power=ac
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import re
import logging
# Import Salt Libs
import salt.utils.platform
log = logging.getLogger(__name__)
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _get_current_scheme():
cmd = 'powercfg /getactivescheme'
out = __salt__['cmd.run'](cmd, python_shell=False)
matches = re.search(r'GUID: (.*) \(', out)
return matches.groups()[0].strip()
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
out = s
break
else:
out = split[0]
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60}
def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout)
def get_monitor_timeout(scheme=None):
'''
Get the current monitor timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_monitor_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_VIDEO',
subguid='VIDEOIDLE',
safe_name='Turn off display after')
def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout)
def get_disk_timeout(scheme=None):
'''
Get the current disk timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_disk_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_DISK',
subguid='DISKIDLE',
safe_name='Turn off hard disk after')
def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout)
def get_standby_timeout(scheme=None):
'''
Get the current standby timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_standby_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='STANDBYIDLE',
safe_name='Sleep after')
def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout)
def get_hibernate_timeout(scheme=None):
'''
Get the current hibernate timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_hibernate_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='HIBERNATEIDLE',
safe_name='Hibernate after')
|
saltstack/salt
|
salt/modules/win_powercfg.py
|
set_monitor_timeout
|
python
|
def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout)
|
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L84-L123
|
[
"def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):\n '''\n Sets the AC/DC values of a setting with the given power for the given scheme\n '''\n if scheme is None:\n scheme = _get_current_scheme()\n\n cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \\\n ''.format(power, scheme, sub_group, setting_guid, value * 60)\n return __salt__['cmd.retcode'](cmd, python_shell=False) == 0\n"
] |
# -*- coding: utf-8 -*-
'''
This module allows you to control the power settings of a windows minion via
powercfg.
.. versionadded:: 2015.8.0
.. code-block:: bash
# Set monitor to never turn off on Battery power
salt '*' powercfg.set_monitor_timeout 0 power=dc
# Set disk timeout to 120 minutes on AC power
salt '*' powercfg.set_disk_timeout 120 power=ac
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import re
import logging
# Import Salt Libs
import salt.utils.platform
log = logging.getLogger(__name__)
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _get_current_scheme():
cmd = 'powercfg /getactivescheme'
out = __salt__['cmd.run'](cmd, python_shell=False)
matches = re.search(r'GUID: (.*) \(', out)
return matches.groups()[0].strip()
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
out = s
break
else:
out = split[0]
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60}
def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the AC/DC values of a setting with the given power for the given scheme
'''
if scheme is None:
scheme = _get_current_scheme()
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
def get_monitor_timeout(scheme=None):
'''
Get the current monitor timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_monitor_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_VIDEO',
subguid='VIDEOIDLE',
safe_name='Turn off display after')
def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout)
def get_disk_timeout(scheme=None):
'''
Get the current disk timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_disk_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_DISK',
subguid='DISKIDLE',
safe_name='Turn off hard disk after')
def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout)
def get_standby_timeout(scheme=None):
'''
Get the current standby timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_standby_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='STANDBYIDLE',
safe_name='Sleep after')
def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout)
def get_hibernate_timeout(scheme=None):
'''
Get the current hibernate timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_hibernate_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='HIBERNATEIDLE',
safe_name='Hibernate after')
|
saltstack/salt
|
salt/modules/win_powercfg.py
|
set_disk_timeout
|
python
|
def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout)
|
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L156-L195
|
[
"def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):\n '''\n Sets the AC/DC values of a setting with the given power for the given scheme\n '''\n if scheme is None:\n scheme = _get_current_scheme()\n\n cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \\\n ''.format(power, scheme, sub_group, setting_guid, value * 60)\n return __salt__['cmd.retcode'](cmd, python_shell=False) == 0\n"
] |
# -*- coding: utf-8 -*-
'''
This module allows you to control the power settings of a windows minion via
powercfg.
.. versionadded:: 2015.8.0
.. code-block:: bash
# Set monitor to never turn off on Battery power
salt '*' powercfg.set_monitor_timeout 0 power=dc
# Set disk timeout to 120 minutes on AC power
salt '*' powercfg.set_disk_timeout 120 power=ac
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import re
import logging
# Import Salt Libs
import salt.utils.platform
log = logging.getLogger(__name__)
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _get_current_scheme():
cmd = 'powercfg /getactivescheme'
out = __salt__['cmd.run'](cmd, python_shell=False)
matches = re.search(r'GUID: (.*) \(', out)
return matches.groups()[0].strip()
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
out = s
break
else:
out = split[0]
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60}
def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the AC/DC values of a setting with the given power for the given scheme
'''
if scheme is None:
scheme = _get_current_scheme()
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout)
def get_monitor_timeout(scheme=None):
'''
Get the current monitor timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_monitor_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_VIDEO',
subguid='VIDEOIDLE',
safe_name='Turn off display after')
def get_disk_timeout(scheme=None):
'''
Get the current disk timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_disk_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_DISK',
subguid='DISKIDLE',
safe_name='Turn off hard disk after')
def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout)
def get_standby_timeout(scheme=None):
'''
Get the current standby timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_standby_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='STANDBYIDLE',
safe_name='Sleep after')
def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout)
def get_hibernate_timeout(scheme=None):
'''
Get the current hibernate timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_hibernate_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='HIBERNATEIDLE',
safe_name='Hibernate after')
|
saltstack/salt
|
salt/modules/win_powercfg.py
|
set_standby_timeout
|
python
|
def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout)
|
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L228-L267
|
[
"def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):\n '''\n Sets the AC/DC values of a setting with the given power for the given scheme\n '''\n if scheme is None:\n scheme = _get_current_scheme()\n\n cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \\\n ''.format(power, scheme, sub_group, setting_guid, value * 60)\n return __salt__['cmd.retcode'](cmd, python_shell=False) == 0\n"
] |
# -*- coding: utf-8 -*-
'''
This module allows you to control the power settings of a windows minion via
powercfg.
.. versionadded:: 2015.8.0
.. code-block:: bash
# Set monitor to never turn off on Battery power
salt '*' powercfg.set_monitor_timeout 0 power=dc
# Set disk timeout to 120 minutes on AC power
salt '*' powercfg.set_disk_timeout 120 power=ac
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import re
import logging
# Import Salt Libs
import salt.utils.platform
log = logging.getLogger(__name__)
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _get_current_scheme():
cmd = 'powercfg /getactivescheme'
out = __salt__['cmd.run'](cmd, python_shell=False)
matches = re.search(r'GUID: (.*) \(', out)
return matches.groups()[0].strip()
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
out = s
break
else:
out = split[0]
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60}
def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the AC/DC values of a setting with the given power for the given scheme
'''
if scheme is None:
scheme = _get_current_scheme()
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout)
def get_monitor_timeout(scheme=None):
'''
Get the current monitor timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_monitor_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_VIDEO',
subguid='VIDEOIDLE',
safe_name='Turn off display after')
def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout)
def get_disk_timeout(scheme=None):
'''
Get the current disk timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_disk_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_DISK',
subguid='DISKIDLE',
safe_name='Turn off hard disk after')
def get_standby_timeout(scheme=None):
'''
Get the current standby timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_standby_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='STANDBYIDLE',
safe_name='Sleep after')
def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout)
def get_hibernate_timeout(scheme=None):
'''
Get the current hibernate timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_hibernate_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='HIBERNATEIDLE',
safe_name='Hibernate after')
|
saltstack/salt
|
salt/modules/win_powercfg.py
|
set_hibernate_timeout
|
python
|
def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout)
|
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L299-L338
|
[
"def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):\n '''\n Sets the AC/DC values of a setting with the given power for the given scheme\n '''\n if scheme is None:\n scheme = _get_current_scheme()\n\n cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \\\n ''.format(power, scheme, sub_group, setting_guid, value * 60)\n return __salt__['cmd.retcode'](cmd, python_shell=False) == 0\n"
] |
# -*- coding: utf-8 -*-
'''
This module allows you to control the power settings of a windows minion via
powercfg.
.. versionadded:: 2015.8.0
.. code-block:: bash
# Set monitor to never turn off on Battery power
salt '*' powercfg.set_monitor_timeout 0 power=dc
# Set disk timeout to 120 minutes on AC power
salt '*' powercfg.set_disk_timeout 120 power=ac
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import re
import logging
# Import Salt Libs
import salt.utils.platform
log = logging.getLogger(__name__)
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if not salt.utils.platform.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _get_current_scheme():
cmd = 'powercfg /getactivescheme'
out = __salt__['cmd.run'](cmd, python_shell=False)
matches = re.search(r'GUID: (.*) \(', out)
return matches.groups()[0].strip()
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
out = s
break
else:
out = split[0]
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60}
def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the AC/DC values of a setting with the given power for the given scheme
'''
if scheme is None:
scheme = _get_current_scheme()
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout)
def get_monitor_timeout(scheme=None):
'''
Get the current monitor timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_monitor_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_VIDEO',
subguid='VIDEOIDLE',
safe_name='Turn off display after')
def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout)
def get_disk_timeout(scheme=None):
'''
Get the current disk timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_disk_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_DISK',
subguid='DISKIDLE',
safe_name='Turn off hard disk after')
def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
'''
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout)
def get_standby_timeout(scheme=None):
'''
Get the current standby timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_standby_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='STANDBYIDLE',
safe_name='Sleep after')
def get_hibernate_timeout(scheme=None):
'''
Get the current hibernate timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_hibernate_timeout
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='HIBERNATEIDLE',
safe_name='Hibernate after')
|
saltstack/salt
|
salt/states/pagerduty_schedule.py
|
present
|
python
|
def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a pagerduty schedule exists.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/schedules/create.
This means that most arguments are in a dict called "schedule."
User id's can be pagerduty id, or name, or email address.
'''
# for convenience, we accept id, name, or email as the user id.
kwargs['schedule']['name'] = kwargs['name'] # match PD API structure
for schedule_layer in kwargs['schedule']['schedule_layers']:
for user in schedule_layer['users']:
u = __salt__['pagerduty_util.get_resource']('users',
user['user']['id'],
['email', 'name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if u is None:
raise Exception('unknown user: {0}'.format(user))
user['user']['id'] = u['id']
r = __salt__['pagerduty_util.resource_present']('schedules',
['name', 'id'],
_diff,
profile,
subdomain,
api_key,
**kwargs)
return r
|
Ensure that a pagerduty schedule exists.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/schedules/create.
This means that most arguments are in a dict called "schedule."
User id's can be pagerduty id, or name, or email address.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_schedule.py#L48-L77
| null |
# -*- coding: utf-8 -*-
'''
Manage PagerDuty schedules.
Example:
.. code-block:: yaml
ensure test schedule:
pagerduty_schedule.present:
- name: 'bruce test schedule level1'
- schedule:
name: 'bruce test schedule level1'
time_zone: 'Pacific Time (US & Canada)'
schedule_layers:
- name: 'Schedule Layer 1'
start: '2015-01-01T00:00:00'
users:
- user:
'id': 'Bruce TestUser1'
member_order: 1
- user:
'id': 'Bruce TestUser2'
member_order: 2
- user:
'id': 'bruce+test3@lyft.com'
member_order: 3
- user:
'id': 'bruce+test4@lyft.com'
member_order: 4
rotation_virtual_start: '2015-01-01T00:00:00'
priority: 1
rotation_turn_length_seconds: 604800
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only load if the pygerduty module is available in __salt__
'''
return 'pagerduty_schedule' if 'pagerduty_util.get_resource' in __salt__ else False
def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a pagerduty schedule does not exist.
Name can be pagerduty schedule id or pagerduty schedule name.
'''
r = __salt__['pagerduty_util.resource_absent']('schedules',
['name', 'id'],
profile,
subdomain,
api_key,
**kwargs)
return r
def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
state_data['id'] = resource_object['schedule']['id']
objects_differ = None
# first check all the easy top-level properties: everything except the schedule_layers.
for k, v in state_data['schedule'].items():
if k == 'schedule_layers':
continue
if v != resource_object['schedule'][k]:
objects_differ = '{0} {1} {2}'.format(k, v, resource_object['schedule'][k])
break
# check schedule_layers
if not objects_differ:
for layer in state_data['schedule']['schedule_layers']:
# find matching layer name
resource_layer = None
for resource_layer in resource_object['schedule']['schedule_layers']:
found = False
if layer['name'] == resource_layer['name']:
found = True
break
if not found:
objects_differ = 'layer {0} missing'.format(layer['name'])
break
# set the id, so that we will update this layer instead of creating a new one
layer['id'] = resource_layer['id']
# compare contents of layer and resource_layer
for k, v in layer.items():
if k == 'users':
continue
if k == 'start':
continue
if v != resource_layer[k]:
objects_differ = 'layer {0} key {1} {2} != {3}'.format(layer['name'], k, v, resource_layer[k])
break
if objects_differ:
break
# compare layer['users']
if len(layer['users']) != len(resource_layer['users']):
objects_differ = 'num users in layer {0} {1} != {2}'.format(layer['name'], len(layer['users']), len(resource_layer['users']))
break
for user1 in layer['users']:
found = False
user2 = None
for user2 in resource_layer['users']:
# deal with PD API bug: when you submit member_order=N, you get back member_order=N+1
if user1['member_order'] == user2['member_order'] - 1:
found = True
break
if not found:
objects_differ = 'layer {0} no one with member_order {1}'.format(layer['name'], user1['member_order'])
break
if user1['user']['id'] != user2['user']['id']:
objects_differ = 'layer {0} user at member_order {1} {2} != {3}'.format(layer['name'],
user1['member_order'],
user1['user']['id'],
user2['user']['id'])
break
if objects_differ:
return state_data
else:
return {}
|
saltstack/salt
|
salt/states/pagerduty_schedule.py
|
_diff
|
python
|
def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
state_data['id'] = resource_object['schedule']['id']
objects_differ = None
# first check all the easy top-level properties: everything except the schedule_layers.
for k, v in state_data['schedule'].items():
if k == 'schedule_layers':
continue
if v != resource_object['schedule'][k]:
objects_differ = '{0} {1} {2}'.format(k, v, resource_object['schedule'][k])
break
# check schedule_layers
if not objects_differ:
for layer in state_data['schedule']['schedule_layers']:
# find matching layer name
resource_layer = None
for resource_layer in resource_object['schedule']['schedule_layers']:
found = False
if layer['name'] == resource_layer['name']:
found = True
break
if not found:
objects_differ = 'layer {0} missing'.format(layer['name'])
break
# set the id, so that we will update this layer instead of creating a new one
layer['id'] = resource_layer['id']
# compare contents of layer and resource_layer
for k, v in layer.items():
if k == 'users':
continue
if k == 'start':
continue
if v != resource_layer[k]:
objects_differ = 'layer {0} key {1} {2} != {3}'.format(layer['name'], k, v, resource_layer[k])
break
if objects_differ:
break
# compare layer['users']
if len(layer['users']) != len(resource_layer['users']):
objects_differ = 'num users in layer {0} {1} != {2}'.format(layer['name'], len(layer['users']), len(resource_layer['users']))
break
for user1 in layer['users']:
found = False
user2 = None
for user2 in resource_layer['users']:
# deal with PD API bug: when you submit member_order=N, you get back member_order=N+1
if user1['member_order'] == user2['member_order'] - 1:
found = True
break
if not found:
objects_differ = 'layer {0} no one with member_order {1}'.format(layer['name'], user1['member_order'])
break
if user1['user']['id'] != user2['user']['id']:
objects_differ = 'layer {0} user at member_order {1} {2} != {3}'.format(layer['name'],
user1['member_order'],
user1['user']['id'],
user2['user']['id'])
break
if objects_differ:
return state_data
else:
return {}
|
helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_schedule.py#L94-L163
| null |
# -*- coding: utf-8 -*-
'''
Manage PagerDuty schedules.
Example:
.. code-block:: yaml
ensure test schedule:
pagerduty_schedule.present:
- name: 'bruce test schedule level1'
- schedule:
name: 'bruce test schedule level1'
time_zone: 'Pacific Time (US & Canada)'
schedule_layers:
- name: 'Schedule Layer 1'
start: '2015-01-01T00:00:00'
users:
- user:
'id': 'Bruce TestUser1'
member_order: 1
- user:
'id': 'Bruce TestUser2'
member_order: 2
- user:
'id': 'bruce+test3@lyft.com'
member_order: 3
- user:
'id': 'bruce+test4@lyft.com'
member_order: 4
rotation_virtual_start: '2015-01-01T00:00:00'
priority: 1
rotation_turn_length_seconds: 604800
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only load if the pygerduty module is available in __salt__
'''
return 'pagerduty_schedule' if 'pagerduty_util.get_resource' in __salt__ else False
def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a pagerduty schedule exists.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/schedules/create.
This means that most arguments are in a dict called "schedule."
User id's can be pagerduty id, or name, or email address.
'''
# for convenience, we accept id, name, or email as the user id.
kwargs['schedule']['name'] = kwargs['name'] # match PD API structure
for schedule_layer in kwargs['schedule']['schedule_layers']:
for user in schedule_layer['users']:
u = __salt__['pagerduty_util.get_resource']('users',
user['user']['id'],
['email', 'name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if u is None:
raise Exception('unknown user: {0}'.format(user))
user['user']['id'] = u['id']
r = __salt__['pagerduty_util.resource_present']('schedules',
['name', 'id'],
_diff,
profile,
subdomain,
api_key,
**kwargs)
return r
def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a pagerduty schedule does not exist.
Name can be pagerduty schedule id or pagerduty schedule name.
'''
r = __salt__['pagerduty_util.resource_absent']('schedules',
['name', 'id'],
profile,
subdomain,
api_key,
**kwargs)
return r
|
saltstack/salt
|
salt/modules/cron.py
|
_cron_id
|
python
|
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
|
SAFETYBELT, Only set if we really have an identifier
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L52-L60
|
[
"def _ensure_string(val):\n # Account for cases where the identifier is not a string\n # which would cause to_unicode to fail.\n if not isinstance(val, six.string_types):\n val = str(val) # future lint: enable=blacklisted-function\n try:\n return salt.utils.stringutils.to_unicode(val)\n except TypeError:\n return ''\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
_cron_matched
|
python
|
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
|
Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L63-L105
|
[
"def _ensure_string(val):\n # Account for cases where the identifier is not a string\n # which would cause to_unicode to fail.\n if not isinstance(val, six.string_types):\n val = str(val) # future lint: enable=blacklisted-function\n try:\n return salt.utils.stringutils.to_unicode(val)\n except TypeError:\n return ''\n",
"def _cron_id(cron):\n '''SAFETYBELT, Only set if we really have an identifier'''\n cid = None\n if cron['identifier']:\n cid = cron['identifier']\n else:\n cid = SALT_CRON_NO_IDENTIFIER\n if cid:\n return _ensure_string(cid)\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
_render_tab
|
python
|
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
|
Takes a tab list structure and renders it to a list for applying it to
a file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L119-L177
| null |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
_get_cron_cmdstr
|
python
|
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
|
Returns a format string, to be used to build a crontab command.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L180-L188
| null |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
write_cron_file
|
python
|
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
|
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L198-L220
|
[
"def _get_cron_cmdstr(path, user=None):\n '''\n Returns a format string, to be used to build a crontab command.\n '''\n if user:\n cmd = 'crontab -u {0}'.format(user)\n else:\n cmd = 'crontab'\n return '{0} {1}'.format(cmd, path)\n",
"def _check_instance_uid_match(user):\n '''\n Returns true if running instance's UID matches the specified user UID\n '''\n return os.geteuid() == __salt__['file.user_to_uid'](user)\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
_write_cron_lines
|
python
|
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
|
Takes a list of lines to be committed to a user's crontab and writes it
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L248-L267
|
[
"def mkstemp(*args, **kwargs):\n '''\n Helper function which does exactly what ``tempfile.mkstemp()`` does but\n accepts another argument, ``close_fd``, which, by default, is true and closes\n the fd before returning the file path. Something commonly done throughout\n Salt's code.\n '''\n if 'prefix' not in kwargs:\n kwargs['prefix'] = '__salt.tmp.'\n close_fd = kwargs.pop('close_fd', True)\n fd_, f_path = tempfile.mkstemp(*args, **kwargs)\n if close_fd is False:\n return fd_, f_path\n os.close(fd_)\n del fd_\n return f_path\n",
"def _get_cron_cmdstr(path, user=None):\n '''\n Returns a format string, to be used to build a crontab command.\n '''\n if user:\n cmd = 'crontab -u {0}'.format(user)\n else:\n cmd = 'crontab'\n return '{0} {1}'.format(cmd, path)\n",
"def _check_instance_uid_match(user):\n '''\n Returns true if running instance's UID matches the specified user UID\n '''\n return os.geteuid() == __salt__['file.user_to_uid'](user)\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
_date_time_match
|
python
|
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
|
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L270-L277
| null |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
raw_cron
|
python
|
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
|
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L280-L312
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def _check_instance_uid_match(user):\n '''\n Returns true if running instance's UID matches the specified user UID\n '''\n return os.geteuid() == __salt__['file.user_to_uid'](user)\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
list_tab
|
python
|
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
|
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L315-L404
|
[
"def raw_cron(user):\n '''\n Return the contents of the user's crontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.raw_cron root\n '''\n if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):\n cmd = 'crontab -l'\n # Preserve line endings\n lines = salt.utils.data.decode(\n __salt__['cmd.run_stdout'](cmd,\n runas=user,\n ignore_retcode=True,\n rstrip=False,\n python_shell=False)\n ).splitlines(True)\n else:\n cmd = 'crontab -u {0} -l'.format(user)\n # Preserve line endings\n lines = salt.utils.data.decode(\n __salt__['cmd.run_stdout'](cmd,\n ignore_retcode=True,\n rstrip=False,\n python_shell=False)\n ).splitlines(True)\n\n if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):\n del lines[0:3]\n return ''.join(lines)\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
get_entry
|
python
|
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
|
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L411-L438
|
[
"def list_tab(user):\n '''\n Return the contents of the specified user's crontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.list_tab root\n '''\n data = raw_cron(user)\n ret = {'pre': [],\n 'crons': [],\n 'special': [],\n 'env': []}\n flag = False\n comment = None\n identifier = None\n for line in data.splitlines():\n if line == '# Lines below here are managed by Salt, do not edit':\n flag = True\n continue\n if flag:\n commented_cron_job = False\n if line.startswith('#DISABLED#'):\n # It's a commented cron job\n line = line[10:]\n commented_cron_job = True\n if line.startswith('@'):\n # Its a \"special\" line\n dat = {}\n comps = line.split()\n if len(comps) < 2:\n # Invalid line\n continue\n dat['spec'] = comps[0]\n dat['cmd'] = ' '.join(comps[1:])\n dat['identifier'] = identifier\n dat['comment'] = comment\n dat['commented'] = False\n if commented_cron_job:\n dat['commented'] = True\n ret['special'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n elif line.startswith('#'):\n # It's a comment! Catch it!\n comment_line = line.lstrip('# ')\n\n # load the identifier if any\n if SALT_CRON_IDENTIFIER in comment_line:\n parts = comment_line.split(SALT_CRON_IDENTIFIER)\n comment_line = parts[0].rstrip()\n # skip leading :\n if len(parts[1]) > 1:\n identifier = parts[1][1:]\n\n if comment is None:\n comment = comment_line\n else:\n comment += '\\n' + comment_line\n elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):\n # Appears to be a ENV setup line\n comps = line.split('=', 1)\n dat = {}\n dat['name'] = comps[0]\n dat['value'] = comps[1]\n ret['env'].append(dat)\n elif len(line.split(' ')) > 5:\n # Appears to be a standard cron line\n comps = line.split(' ')\n dat = {'minute': comps[0],\n 'hour': comps[1],\n 'daymonth': comps[2],\n 'month': comps[3],\n 'dayweek': comps[4],\n 'identifier': identifier,\n 'cmd': ' '.join(comps[5:]),\n 'comment': comment,\n 'commented': False}\n if commented_cron_job:\n dat['commented'] = True\n ret['crons'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n else:\n ret['pre'].append(line)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
set_special
|
python
|
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
|
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L441-L516
|
[
"def _needs_change(old, new):\n if old != new:\n if new == 'random':\n # Allow switch from '*' or not present to 'random'\n if old == '*':\n return True\n elif new is not None:\n return True\n return False\n",
"def _cron_matched(cron, cmd, identifier=None):\n '''Check if:\n - we find a cron with same cmd, old state behavior\n - but also be smart enough to remove states changed crons where we do\n not removed priorly by a cron.absent by matching on the provided\n identifier.\n We assure retrocompatibility by only checking on identifier if\n and only if an identifier was set on the serialized crontab\n '''\n ret, id_matched = False, None\n cid = _cron_id(cron)\n if cid:\n if not identifier:\n identifier = SALT_CRON_NO_IDENTIFIER\n eidentifier = _ensure_string(identifier)\n # old style second round\n # after saving crontab, we must check that if\n # we have not the same command, but the default id\n # to not set that as a match\n if (\n cron.get('cmd', None) != cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and eidentifier == SALT_CRON_NO_IDENTIFIER\n ):\n id_matched = False\n else:\n # on saving, be sure not to overwrite a cron\n # with specific identifier but also track\n # crons where command is the same\n # but with the default if that we gonna overwrite\n if (\n cron.get('cmd', None) == cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and identifier\n ):\n cid = eidentifier\n id_matched = eidentifier == cid\n if (\n ((id_matched is None) and cmd == cron.get('cmd', None))\n or id_matched\n ):\n ret = True\n return ret\n",
"def _cron_id(cron):\n '''SAFETYBELT, Only set if we really have an identifier'''\n cid = None\n if cron['identifier']:\n cid = cron['identifier']\n else:\n cid = SALT_CRON_NO_IDENTIFIER\n if cid:\n return _ensure_string(cid)\n",
"def _render_tab(lst):\n '''\n Takes a tab list structure and renders it to a list for applying it to\n a file\n '''\n ret = []\n for pre in lst['pre']:\n ret.append('{0}\\n'.format(pre))\n if ret:\n if ret[-1] != TAG:\n ret.append(TAG)\n else:\n ret.append(TAG)\n for env in lst['env']:\n if (env['value'] is None) or (env['value'] == \"\"):\n ret.append('{0}=\"\"\\n'.format(env['name']))\n else:\n ret.append('{0}={1}\\n'.format(env['name'], env['value']))\n for cron in lst['crons']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2} {3} {4} {5} {6}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['minute'],\n cron['hour'],\n cron['daymonth'],\n cron['month'],\n cron['dayweek'],\n cron['cmd']\n )\n )\n for cron in lst['special']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].rstrip().replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['spec'],\n cron['cmd']\n )\n )\n return ret\n",
"def _write_cron_lines(user, lines):\n '''\n Takes a list of lines to be committed to a user's crontab and writes it\n '''\n lines = [salt.utils.stringutils.to_str(_l) for _l in lines]\n path = salt.utils.files.mkstemp()\n if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):\n # In some cases crontab command should be executed as user rather than root\n with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),\n runas=user,\n python_shell=False)\n else:\n with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),\n python_shell=False)\n os.remove(path)\n return ret\n",
"def list_tab(user):\n '''\n Return the contents of the specified user's crontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.list_tab root\n '''\n data = raw_cron(user)\n ret = {'pre': [],\n 'crons': [],\n 'special': [],\n 'env': []}\n flag = False\n comment = None\n identifier = None\n for line in data.splitlines():\n if line == '# Lines below here are managed by Salt, do not edit':\n flag = True\n continue\n if flag:\n commented_cron_job = False\n if line.startswith('#DISABLED#'):\n # It's a commented cron job\n line = line[10:]\n commented_cron_job = True\n if line.startswith('@'):\n # Its a \"special\" line\n dat = {}\n comps = line.split()\n if len(comps) < 2:\n # Invalid line\n continue\n dat['spec'] = comps[0]\n dat['cmd'] = ' '.join(comps[1:])\n dat['identifier'] = identifier\n dat['comment'] = comment\n dat['commented'] = False\n if commented_cron_job:\n dat['commented'] = True\n ret['special'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n elif line.startswith('#'):\n # It's a comment! Catch it!\n comment_line = line.lstrip('# ')\n\n # load the identifier if any\n if SALT_CRON_IDENTIFIER in comment_line:\n parts = comment_line.split(SALT_CRON_IDENTIFIER)\n comment_line = parts[0].rstrip()\n # skip leading :\n if len(parts[1]) > 1:\n identifier = parts[1][1:]\n\n if comment is None:\n comment = comment_line\n else:\n comment += '\\n' + comment_line\n elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):\n # Appears to be a ENV setup line\n comps = line.split('=', 1)\n dat = {}\n dat['name'] = comps[0]\n dat['value'] = comps[1]\n ret['env'].append(dat)\n elif len(line.split(' ')) > 5:\n # Appears to be a standard cron line\n comps = line.split(' ')\n dat = {'minute': comps[0],\n 'hour': comps[1],\n 'daymonth': comps[2],\n 'month': comps[3],\n 'dayweek': comps[4],\n 'identifier': identifier,\n 'cmd': ' '.join(comps[5:]),\n 'comment': comment,\n 'commented': False}\n if commented_cron_job:\n dat['commented'] = True\n ret['crons'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n else:\n ret['pre'].append(line)\n return ret\n",
"def set_special(user,\n special,\n cmd,\n commented=False,\n comment=None,\n identifier=None):\n '''\n Set up a special command in the crontab.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.set_special root @hourly 'echo foobar'\n '''\n lst = list_tab(user)\n for cron in lst['special']:\n cid = _cron_id(cron)\n if _cron_matched(cron, cmd, identifier):\n test_setted_id = (\n cron['identifier'] is None\n and SALT_CRON_NO_IDENTIFIER\n or cron['identifier'])\n tests = [(cron['comment'], comment),\n (cron['commented'], commented),\n (identifier, test_setted_id),\n (cron['spec'], special)]\n if cid or identifier:\n tests.append((cron['cmd'], cmd))\n if any([_needs_change(x, y) for x, y in tests]):\n rm_special(user, cmd, identifier=cid)\n\n # Use old values when setting the new job if there was no\n # change needed for a given parameter\n if not _needs_change(cron['spec'], special):\n special = cron['spec']\n if not _needs_change(cron['commented'], commented):\n commented = cron['commented']\n if not _needs_change(cron['comment'], comment):\n comment = cron['comment']\n if not _needs_change(cron['cmd'], cmd):\n cmd = cron['cmd']\n if (\n cid == SALT_CRON_NO_IDENTIFIER\n ):\n if identifier:\n cid = identifier\n if (\n cid == SALT_CRON_NO_IDENTIFIER\n and cron['identifier'] is None\n ):\n cid = None\n cron['identifier'] = cid\n if not cid or (\n cid and not _needs_change(cid, identifier)\n ):\n identifier = cid\n jret = set_special(user, special, cmd, commented=commented,\n comment=comment, identifier=identifier)\n if jret == 'new':\n return 'updated'\n else:\n return jret\n return 'present'\n cron = {'spec': special,\n 'cmd': cmd,\n 'identifier': identifier,\n 'comment': comment,\n 'commented': commented}\n lst['special'].append(cron)\n\n comdat = _write_cron_lines(user, _render_tab(lst))\n if comdat['retcode']:\n # Failed to commit, return the error\n return comdat['stderr']\n return 'new'\n",
"def rm_special(user, cmd, special=None, identifier=None):\n '''\n Remove a special cron job for a specified user.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.rm_special root /usr/bin/foo\n '''\n lst = list_tab(user)\n ret = 'absent'\n rm_ = None\n for ind in range(len(lst['special'])):\n if rm_ is not None:\n break\n if _cron_matched(lst['special'][ind], cmd, identifier=identifier):\n if special is None:\n # No special param was specified\n rm_ = ind\n else:\n if lst['special'][ind]['spec'] == special:\n rm_ = ind\n if rm_ is not None:\n lst['special'].pop(rm_)\n ret = 'removed'\n comdat = _write_cron_lines(user, _render_tab(lst))\n if comdat['retcode']:\n # Failed to commit, return the error\n return comdat['stderr']\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
_get_cron_date_time
|
python
|
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
|
Returns a dict of date/time values to be used in a cron entry
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L519-L558
| null |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
set_job
|
python
|
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
|
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L561-L661
|
[
"def rm_job(user,\n cmd,\n minute=None,\n hour=None,\n daymonth=None,\n month=None,\n dayweek=None,\n identifier=None):\n '''\n Remove a cron job for a specified user. If any of the day/time params are\n specified, the job will only be removed if the specified params match.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.rm_job root /usr/local/weekly\n salt '*' cron.rm_job root /usr/bin/foo dayweek=1\n '''\n lst = list_tab(user)\n ret = 'absent'\n rm_ = None\n for ind in range(len(lst['crons'])):\n if rm_ is not None:\n break\n if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):\n if not any([x is not None\n for x in (minute, hour, daymonth, month, dayweek)]):\n # No date/time params were specified\n rm_ = ind\n else:\n if _date_time_match(lst['crons'][ind],\n minute=minute,\n hour=hour,\n daymonth=daymonth,\n month=month,\n dayweek=dayweek):\n rm_ = ind\n if rm_ is not None:\n lst['crons'].pop(rm_)\n ret = 'removed'\n comdat = _write_cron_lines(user, _render_tab(lst))\n if comdat['retcode']:\n # Failed to commit, return the error\n return comdat['stderr']\n return ret\n",
"def _needs_change(old, new):\n if old != new:\n if new == 'random':\n # Allow switch from '*' or not present to 'random'\n if old == '*':\n return True\n elif new is not None:\n return True\n return False\n",
"def _cron_matched(cron, cmd, identifier=None):\n '''Check if:\n - we find a cron with same cmd, old state behavior\n - but also be smart enough to remove states changed crons where we do\n not removed priorly by a cron.absent by matching on the provided\n identifier.\n We assure retrocompatibility by only checking on identifier if\n and only if an identifier was set on the serialized crontab\n '''\n ret, id_matched = False, None\n cid = _cron_id(cron)\n if cid:\n if not identifier:\n identifier = SALT_CRON_NO_IDENTIFIER\n eidentifier = _ensure_string(identifier)\n # old style second round\n # after saving crontab, we must check that if\n # we have not the same command, but the default id\n # to not set that as a match\n if (\n cron.get('cmd', None) != cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and eidentifier == SALT_CRON_NO_IDENTIFIER\n ):\n id_matched = False\n else:\n # on saving, be sure not to overwrite a cron\n # with specific identifier but also track\n # crons where command is the same\n # but with the default if that we gonna overwrite\n if (\n cron.get('cmd', None) == cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and identifier\n ):\n cid = eidentifier\n id_matched = eidentifier == cid\n if (\n ((id_matched is None) and cmd == cron.get('cmd', None))\n or id_matched\n ):\n ret = True\n return ret\n",
"def _cron_id(cron):\n '''SAFETYBELT, Only set if we really have an identifier'''\n cid = None\n if cron['identifier']:\n cid = cron['identifier']\n else:\n cid = SALT_CRON_NO_IDENTIFIER\n if cid:\n return _ensure_string(cid)\n",
"def _render_tab(lst):\n '''\n Takes a tab list structure and renders it to a list for applying it to\n a file\n '''\n ret = []\n for pre in lst['pre']:\n ret.append('{0}\\n'.format(pre))\n if ret:\n if ret[-1] != TAG:\n ret.append(TAG)\n else:\n ret.append(TAG)\n for env in lst['env']:\n if (env['value'] is None) or (env['value'] == \"\"):\n ret.append('{0}=\"\"\\n'.format(env['name']))\n else:\n ret.append('{0}={1}\\n'.format(env['name'], env['value']))\n for cron in lst['crons']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2} {3} {4} {5} {6}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['minute'],\n cron['hour'],\n cron['daymonth'],\n cron['month'],\n cron['dayweek'],\n cron['cmd']\n )\n )\n for cron in lst['special']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].rstrip().replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['spec'],\n cron['cmd']\n )\n )\n return ret\n",
"def _write_cron_lines(user, lines):\n '''\n Takes a list of lines to be committed to a user's crontab and writes it\n '''\n lines = [salt.utils.stringutils.to_str(_l) for _l in lines]\n path = salt.utils.files.mkstemp()\n if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):\n # In some cases crontab command should be executed as user rather than root\n with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),\n runas=user,\n python_shell=False)\n else:\n with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),\n python_shell=False)\n os.remove(path)\n return ret\n",
"def list_tab(user):\n '''\n Return the contents of the specified user's crontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.list_tab root\n '''\n data = raw_cron(user)\n ret = {'pre': [],\n 'crons': [],\n 'special': [],\n 'env': []}\n flag = False\n comment = None\n identifier = None\n for line in data.splitlines():\n if line == '# Lines below here are managed by Salt, do not edit':\n flag = True\n continue\n if flag:\n commented_cron_job = False\n if line.startswith('#DISABLED#'):\n # It's a commented cron job\n line = line[10:]\n commented_cron_job = True\n if line.startswith('@'):\n # Its a \"special\" line\n dat = {}\n comps = line.split()\n if len(comps) < 2:\n # Invalid line\n continue\n dat['spec'] = comps[0]\n dat['cmd'] = ' '.join(comps[1:])\n dat['identifier'] = identifier\n dat['comment'] = comment\n dat['commented'] = False\n if commented_cron_job:\n dat['commented'] = True\n ret['special'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n elif line.startswith('#'):\n # It's a comment! Catch it!\n comment_line = line.lstrip('# ')\n\n # load the identifier if any\n if SALT_CRON_IDENTIFIER in comment_line:\n parts = comment_line.split(SALT_CRON_IDENTIFIER)\n comment_line = parts[0].rstrip()\n # skip leading :\n if len(parts[1]) > 1:\n identifier = parts[1][1:]\n\n if comment is None:\n comment = comment_line\n else:\n comment += '\\n' + comment_line\n elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):\n # Appears to be a ENV setup line\n comps = line.split('=', 1)\n dat = {}\n dat['name'] = comps[0]\n dat['value'] = comps[1]\n ret['env'].append(dat)\n elif len(line.split(' ')) > 5:\n # Appears to be a standard cron line\n comps = line.split(' ')\n dat = {'minute': comps[0],\n 'hour': comps[1],\n 'daymonth': comps[2],\n 'month': comps[3],\n 'dayweek': comps[4],\n 'identifier': identifier,\n 'cmd': ' '.join(comps[5:]),\n 'comment': comment,\n 'commented': False}\n if commented_cron_job:\n dat['commented'] = True\n ret['crons'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n else:\n ret['pre'].append(line)\n return ret\n",
"def _get_cron_date_time(**kwargs):\n '''\n Returns a dict of date/time values to be used in a cron entry\n '''\n # Define ranges (except daymonth, as it depends on the month)\n range_max = {\n 'minute': list(list(range(60))),\n 'hour': list(list(range(24))),\n 'month': list(list(range(1, 13))),\n 'dayweek': list(list(range(7)))\n }\n\n ret = {}\n for param in ('minute', 'hour', 'month', 'dayweek'):\n value = six.text_type(kwargs.get(param, '1')).lower()\n if value == 'random':\n ret[param] = six.text_type(random.sample(range_max[param], 1)[0])\n elif len(value.split(':')) == 2:\n cron_range = sorted(value.split(':'))\n start, end = int(cron_range[0]), int(cron_range[1])\n ret[param] = six.text_type(random.randint(start, end))\n else:\n ret[param] = value\n\n if ret['month'] in '1 3 5 7 8 10 12'.split():\n daymonth_max = 31\n elif ret['month'] in '4 6 9 11'.split():\n daymonth_max = 30\n else:\n # This catches both '2' and '*'\n daymonth_max = 28\n\n daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()\n if daymonth == 'random':\n ret['daymonth'] = \\\n six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])\n else:\n ret['daymonth'] = daymonth\n\n return ret\n",
"def set_job(user,\n minute,\n hour,\n daymonth,\n month,\n dayweek,\n cmd,\n commented=False,\n comment=None,\n identifier=None):\n '''\n Sets a cron job up for a specified user.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly\n '''\n # Scrub the types\n minute = six.text_type(minute).lower()\n hour = six.text_type(hour).lower()\n daymonth = six.text_type(daymonth).lower()\n month = six.text_type(month).lower()\n dayweek = six.text_type(dayweek).lower()\n lst = list_tab(user)\n for cron in lst['crons']:\n cid = _cron_id(cron)\n if _cron_matched(cron, cmd, identifier):\n test_setted_id = (\n cron['identifier'] is None\n and SALT_CRON_NO_IDENTIFIER\n or cron['identifier'])\n tests = [(cron['comment'], comment),\n (cron['commented'], commented),\n (identifier, test_setted_id),\n (cron['minute'], minute),\n (cron['hour'], hour),\n (cron['daymonth'], daymonth),\n (cron['month'], month),\n (cron['dayweek'], dayweek)]\n if cid or identifier:\n tests.append((cron['cmd'], cmd))\n if any([_needs_change(x, y) for x, y in tests]):\n rm_job(user, cmd, identifier=cid)\n\n # Use old values when setting the new job if there was no\n # change needed for a given parameter\n if not _needs_change(cron['minute'], minute):\n minute = cron['minute']\n if not _needs_change(cron['hour'], hour):\n hour = cron['hour']\n if not _needs_change(cron['daymonth'], daymonth):\n daymonth = cron['daymonth']\n if not _needs_change(cron['month'], month):\n month = cron['month']\n if not _needs_change(cron['dayweek'], dayweek):\n dayweek = cron['dayweek']\n if not _needs_change(cron['commented'], commented):\n commented = cron['commented']\n if not _needs_change(cron['comment'], comment):\n comment = cron['comment']\n if not _needs_change(cron['cmd'], cmd):\n cmd = cron['cmd']\n if (\n cid == SALT_CRON_NO_IDENTIFIER\n ):\n if identifier:\n cid = identifier\n if (\n cid == SALT_CRON_NO_IDENTIFIER\n and cron['identifier'] is None\n ):\n cid = None\n cron['identifier'] = cid\n if not cid or (\n cid and not _needs_change(cid, identifier)\n ):\n identifier = cid\n jret = set_job(user, minute, hour, daymonth,\n month, dayweek, cmd, commented=commented,\n comment=comment, identifier=identifier)\n if jret == 'new':\n return 'updated'\n else:\n return jret\n return 'present'\n cron = {'cmd': cmd,\n 'identifier': identifier,\n 'comment': comment,\n 'commented': commented}\n cron.update(_get_cron_date_time(minute=minute, hour=hour,\n daymonth=daymonth, month=month,\n dayweek=dayweek))\n lst['crons'].append(cron)\n\n comdat = _write_cron_lines(user, _render_tab(lst))\n if comdat['retcode']:\n # Failed to commit, return the error\n return comdat['stderr']\n return 'new'\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
rm_special
|
python
|
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L664-L694
|
[
"def _cron_matched(cron, cmd, identifier=None):\n '''Check if:\n - we find a cron with same cmd, old state behavior\n - but also be smart enough to remove states changed crons where we do\n not removed priorly by a cron.absent by matching on the provided\n identifier.\n We assure retrocompatibility by only checking on identifier if\n and only if an identifier was set on the serialized crontab\n '''\n ret, id_matched = False, None\n cid = _cron_id(cron)\n if cid:\n if not identifier:\n identifier = SALT_CRON_NO_IDENTIFIER\n eidentifier = _ensure_string(identifier)\n # old style second round\n # after saving crontab, we must check that if\n # we have not the same command, but the default id\n # to not set that as a match\n if (\n cron.get('cmd', None) != cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and eidentifier == SALT_CRON_NO_IDENTIFIER\n ):\n id_matched = False\n else:\n # on saving, be sure not to overwrite a cron\n # with specific identifier but also track\n # crons where command is the same\n # but with the default if that we gonna overwrite\n if (\n cron.get('cmd', None) == cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and identifier\n ):\n cid = eidentifier\n id_matched = eidentifier == cid\n if (\n ((id_matched is None) and cmd == cron.get('cmd', None))\n or id_matched\n ):\n ret = True\n return ret\n",
"def _render_tab(lst):\n '''\n Takes a tab list structure and renders it to a list for applying it to\n a file\n '''\n ret = []\n for pre in lst['pre']:\n ret.append('{0}\\n'.format(pre))\n if ret:\n if ret[-1] != TAG:\n ret.append(TAG)\n else:\n ret.append(TAG)\n for env in lst['env']:\n if (env['value'] is None) or (env['value'] == \"\"):\n ret.append('{0}=\"\"\\n'.format(env['name']))\n else:\n ret.append('{0}={1}\\n'.format(env['name'], env['value']))\n for cron in lst['crons']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2} {3} {4} {5} {6}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['minute'],\n cron['hour'],\n cron['daymonth'],\n cron['month'],\n cron['dayweek'],\n cron['cmd']\n )\n )\n for cron in lst['special']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].rstrip().replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['spec'],\n cron['cmd']\n )\n )\n return ret\n",
"def _write_cron_lines(user, lines):\n '''\n Takes a list of lines to be committed to a user's crontab and writes it\n '''\n lines = [salt.utils.stringutils.to_str(_l) for _l in lines]\n path = salt.utils.files.mkstemp()\n if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):\n # In some cases crontab command should be executed as user rather than root\n with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),\n runas=user,\n python_shell=False)\n else:\n with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),\n python_shell=False)\n os.remove(path)\n return ret\n",
"def list_tab(user):\n '''\n Return the contents of the specified user's crontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.list_tab root\n '''\n data = raw_cron(user)\n ret = {'pre': [],\n 'crons': [],\n 'special': [],\n 'env': []}\n flag = False\n comment = None\n identifier = None\n for line in data.splitlines():\n if line == '# Lines below here are managed by Salt, do not edit':\n flag = True\n continue\n if flag:\n commented_cron_job = False\n if line.startswith('#DISABLED#'):\n # It's a commented cron job\n line = line[10:]\n commented_cron_job = True\n if line.startswith('@'):\n # Its a \"special\" line\n dat = {}\n comps = line.split()\n if len(comps) < 2:\n # Invalid line\n continue\n dat['spec'] = comps[0]\n dat['cmd'] = ' '.join(comps[1:])\n dat['identifier'] = identifier\n dat['comment'] = comment\n dat['commented'] = False\n if commented_cron_job:\n dat['commented'] = True\n ret['special'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n elif line.startswith('#'):\n # It's a comment! Catch it!\n comment_line = line.lstrip('# ')\n\n # load the identifier if any\n if SALT_CRON_IDENTIFIER in comment_line:\n parts = comment_line.split(SALT_CRON_IDENTIFIER)\n comment_line = parts[0].rstrip()\n # skip leading :\n if len(parts[1]) > 1:\n identifier = parts[1][1:]\n\n if comment is None:\n comment = comment_line\n else:\n comment += '\\n' + comment_line\n elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):\n # Appears to be a ENV setup line\n comps = line.split('=', 1)\n dat = {}\n dat['name'] = comps[0]\n dat['value'] = comps[1]\n ret['env'].append(dat)\n elif len(line.split(' ')) > 5:\n # Appears to be a standard cron line\n comps = line.split(' ')\n dat = {'minute': comps[0],\n 'hour': comps[1],\n 'daymonth': comps[2],\n 'month': comps[3],\n 'dayweek': comps[4],\n 'identifier': identifier,\n 'cmd': ' '.join(comps[5:]),\n 'comment': comment,\n 'commented': False}\n if commented_cron_job:\n dat['commented'] = True\n ret['crons'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n else:\n ret['pre'].append(line)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
rm_job
|
python
|
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L697-L742
|
[
"def _cron_matched(cron, cmd, identifier=None):\n '''Check if:\n - we find a cron with same cmd, old state behavior\n - but also be smart enough to remove states changed crons where we do\n not removed priorly by a cron.absent by matching on the provided\n identifier.\n We assure retrocompatibility by only checking on identifier if\n and only if an identifier was set on the serialized crontab\n '''\n ret, id_matched = False, None\n cid = _cron_id(cron)\n if cid:\n if not identifier:\n identifier = SALT_CRON_NO_IDENTIFIER\n eidentifier = _ensure_string(identifier)\n # old style second round\n # after saving crontab, we must check that if\n # we have not the same command, but the default id\n # to not set that as a match\n if (\n cron.get('cmd', None) != cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and eidentifier == SALT_CRON_NO_IDENTIFIER\n ):\n id_matched = False\n else:\n # on saving, be sure not to overwrite a cron\n # with specific identifier but also track\n # crons where command is the same\n # but with the default if that we gonna overwrite\n if (\n cron.get('cmd', None) == cmd\n and cid == SALT_CRON_NO_IDENTIFIER\n and identifier\n ):\n cid = eidentifier\n id_matched = eidentifier == cid\n if (\n ((id_matched is None) and cmd == cron.get('cmd', None))\n or id_matched\n ):\n ret = True\n return ret\n",
"def _date_time_match(cron, **kwargs):\n '''\n Returns true if the minute, hour, etc. params match their counterparts from\n the dict returned from list_tab().\n '''\n return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])\n or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')\n for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])\n",
"def list_tab(user):\n '''\n Return the contents of the specified user's crontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.list_tab root\n '''\n data = raw_cron(user)\n ret = {'pre': [],\n 'crons': [],\n 'special': [],\n 'env': []}\n flag = False\n comment = None\n identifier = None\n for line in data.splitlines():\n if line == '# Lines below here are managed by Salt, do not edit':\n flag = True\n continue\n if flag:\n commented_cron_job = False\n if line.startswith('#DISABLED#'):\n # It's a commented cron job\n line = line[10:]\n commented_cron_job = True\n if line.startswith('@'):\n # Its a \"special\" line\n dat = {}\n comps = line.split()\n if len(comps) < 2:\n # Invalid line\n continue\n dat['spec'] = comps[0]\n dat['cmd'] = ' '.join(comps[1:])\n dat['identifier'] = identifier\n dat['comment'] = comment\n dat['commented'] = False\n if commented_cron_job:\n dat['commented'] = True\n ret['special'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n elif line.startswith('#'):\n # It's a comment! Catch it!\n comment_line = line.lstrip('# ')\n\n # load the identifier if any\n if SALT_CRON_IDENTIFIER in comment_line:\n parts = comment_line.split(SALT_CRON_IDENTIFIER)\n comment_line = parts[0].rstrip()\n # skip leading :\n if len(parts[1]) > 1:\n identifier = parts[1][1:]\n\n if comment is None:\n comment = comment_line\n else:\n comment += '\\n' + comment_line\n elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):\n # Appears to be a ENV setup line\n comps = line.split('=', 1)\n dat = {}\n dat['name'] = comps[0]\n dat['value'] = comps[1]\n ret['env'].append(dat)\n elif len(line.split(' ')) > 5:\n # Appears to be a standard cron line\n comps = line.split(' ')\n dat = {'minute': comps[0],\n 'hour': comps[1],\n 'daymonth': comps[2],\n 'month': comps[3],\n 'dayweek': comps[4],\n 'identifier': identifier,\n 'cmd': ' '.join(comps[5:]),\n 'comment': comment,\n 'commented': False}\n if commented_cron_job:\n dat['commented'] = True\n ret['crons'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n else:\n ret['pre'].append(line)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
set_env
|
python
|
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
|
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L748-L775
|
[
"def _render_tab(lst):\n '''\n Takes a tab list structure and renders it to a list for applying it to\n a file\n '''\n ret = []\n for pre in lst['pre']:\n ret.append('{0}\\n'.format(pre))\n if ret:\n if ret[-1] != TAG:\n ret.append(TAG)\n else:\n ret.append(TAG)\n for env in lst['env']:\n if (env['value'] is None) or (env['value'] == \"\"):\n ret.append('{0}=\"\"\\n'.format(env['name']))\n else:\n ret.append('{0}={1}\\n'.format(env['name'], env['value']))\n for cron in lst['crons']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2} {3} {4} {5} {6}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['minute'],\n cron['hour'],\n cron['daymonth'],\n cron['month'],\n cron['dayweek'],\n cron['cmd']\n )\n )\n for cron in lst['special']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].rstrip().replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['spec'],\n cron['cmd']\n )\n )\n return ret\n",
"def _write_cron_lines(user, lines):\n '''\n Takes a list of lines to be committed to a user's crontab and writes it\n '''\n lines = [salt.utils.stringutils.to_str(_l) for _l in lines]\n path = salt.utils.files.mkstemp()\n if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):\n # In some cases crontab command should be executed as user rather than root\n with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),\n runas=user,\n python_shell=False)\n else:\n with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),\n python_shell=False)\n os.remove(path)\n return ret\n",
"def list_tab(user):\n '''\n Return the contents of the specified user's crontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.list_tab root\n '''\n data = raw_cron(user)\n ret = {'pre': [],\n 'crons': [],\n 'special': [],\n 'env': []}\n flag = False\n comment = None\n identifier = None\n for line in data.splitlines():\n if line == '# Lines below here are managed by Salt, do not edit':\n flag = True\n continue\n if flag:\n commented_cron_job = False\n if line.startswith('#DISABLED#'):\n # It's a commented cron job\n line = line[10:]\n commented_cron_job = True\n if line.startswith('@'):\n # Its a \"special\" line\n dat = {}\n comps = line.split()\n if len(comps) < 2:\n # Invalid line\n continue\n dat['spec'] = comps[0]\n dat['cmd'] = ' '.join(comps[1:])\n dat['identifier'] = identifier\n dat['comment'] = comment\n dat['commented'] = False\n if commented_cron_job:\n dat['commented'] = True\n ret['special'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n elif line.startswith('#'):\n # It's a comment! Catch it!\n comment_line = line.lstrip('# ')\n\n # load the identifier if any\n if SALT_CRON_IDENTIFIER in comment_line:\n parts = comment_line.split(SALT_CRON_IDENTIFIER)\n comment_line = parts[0].rstrip()\n # skip leading :\n if len(parts[1]) > 1:\n identifier = parts[1][1:]\n\n if comment is None:\n comment = comment_line\n else:\n comment += '\\n' + comment_line\n elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):\n # Appears to be a ENV setup line\n comps = line.split('=', 1)\n dat = {}\n dat['name'] = comps[0]\n dat['value'] = comps[1]\n ret['env'].append(dat)\n elif len(line.split(' ')) > 5:\n # Appears to be a standard cron line\n comps = line.split(' ')\n dat = {'minute': comps[0],\n 'hour': comps[1],\n 'daymonth': comps[2],\n 'month': comps[3],\n 'dayweek': comps[4],\n 'identifier': identifier,\n 'cmd': ' '.join(comps[5:]),\n 'comment': comment,\n 'commented': False}\n if commented_cron_job:\n dat['commented'] = True\n ret['crons'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n else:\n ret['pre'].append(line)\n return ret\n",
"def set_env(user, name, value=None):\n '''\n Set up an environment variable in the crontab.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.set_env root MAILTO user@example.com\n '''\n lst = list_tab(user)\n for env in lst['env']:\n if name == env['name']:\n if value != env['value']:\n rm_env(user, name)\n jret = set_env(user, name, value)\n if jret == 'new':\n return 'updated'\n else:\n return jret\n return 'present'\n env = {'name': name, 'value': value}\n lst['env'].append(env)\n comdat = _write_cron_lines(user, _render_tab(lst))\n if comdat['retcode']:\n # Failed to commit, return the error\n return comdat['stderr']\n return 'new'\n",
"def rm_env(user, name):\n '''\n Remove cron environment variable for a specified user.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.rm_env root MAILTO\n '''\n lst = list_tab(user)\n ret = 'absent'\n rm_ = None\n for ind in range(len(lst['env'])):\n if name == lst['env'][ind]['name']:\n rm_ = ind\n if rm_ is not None:\n lst['env'].pop(rm_)\n ret = 'removed'\n comdat = _write_cron_lines(user, _render_tab(lst))\n if comdat['retcode']:\n # Failed to commit, return the error\n return comdat['stderr']\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
saltstack/salt
|
salt/modules/cron.py
|
rm_env
|
python
|
def rm_env(user, name):
'''
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['env'])):
if name == lst['env'][ind]['name']:
rm_ = ind
if rm_ is not None:
lst['env'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
|
Remove cron environment variable for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_env root MAILTO
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L778-L801
|
[
"def _render_tab(lst):\n '''\n Takes a tab list structure and renders it to a list for applying it to\n a file\n '''\n ret = []\n for pre in lst['pre']:\n ret.append('{0}\\n'.format(pre))\n if ret:\n if ret[-1] != TAG:\n ret.append(TAG)\n else:\n ret.append(TAG)\n for env in lst['env']:\n if (env['value'] is None) or (env['value'] == \"\"):\n ret.append('{0}=\"\"\\n'.format(env['name']))\n else:\n ret.append('{0}={1}\\n'.format(env['name'], env['value']))\n for cron in lst['crons']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2} {3} {4} {5} {6}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['minute'],\n cron['hour'],\n cron['daymonth'],\n cron['month'],\n cron['dayweek'],\n cron['cmd']\n )\n )\n for cron in lst['special']:\n if cron['comment'] is not None or cron['identifier'] is not None:\n comment = '#'\n if cron['comment']:\n comment += ' {0}'.format(\n cron['comment'].rstrip().replace('\\n', '\\n# '))\n if cron['identifier']:\n comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,\n cron['identifier'])\n\n comment += '\\n'\n ret.append(comment)\n ret.append('{0}{1} {2}\\n'.format(\n cron['commented'] is True and '#DISABLED#' or '',\n cron['spec'],\n cron['cmd']\n )\n )\n return ret\n",
"def _write_cron_lines(user, lines):\n '''\n Takes a list of lines to be committed to a user's crontab and writes it\n '''\n lines = [salt.utils.stringutils.to_str(_l) for _l in lines]\n path = salt.utils.files.mkstemp()\n if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):\n # In some cases crontab command should be executed as user rather than root\n with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),\n runas=user,\n python_shell=False)\n else:\n with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:\n fp_.writelines(lines)\n ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),\n python_shell=False)\n os.remove(path)\n return ret\n",
"def list_tab(user):\n '''\n Return the contents of the specified user's crontab\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' cron.list_tab root\n '''\n data = raw_cron(user)\n ret = {'pre': [],\n 'crons': [],\n 'special': [],\n 'env': []}\n flag = False\n comment = None\n identifier = None\n for line in data.splitlines():\n if line == '# Lines below here are managed by Salt, do not edit':\n flag = True\n continue\n if flag:\n commented_cron_job = False\n if line.startswith('#DISABLED#'):\n # It's a commented cron job\n line = line[10:]\n commented_cron_job = True\n if line.startswith('@'):\n # Its a \"special\" line\n dat = {}\n comps = line.split()\n if len(comps) < 2:\n # Invalid line\n continue\n dat['spec'] = comps[0]\n dat['cmd'] = ' '.join(comps[1:])\n dat['identifier'] = identifier\n dat['comment'] = comment\n dat['commented'] = False\n if commented_cron_job:\n dat['commented'] = True\n ret['special'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n elif line.startswith('#'):\n # It's a comment! Catch it!\n comment_line = line.lstrip('# ')\n\n # load the identifier if any\n if SALT_CRON_IDENTIFIER in comment_line:\n parts = comment_line.split(SALT_CRON_IDENTIFIER)\n comment_line = parts[0].rstrip()\n # skip leading :\n if len(parts[1]) > 1:\n identifier = parts[1][1:]\n\n if comment is None:\n comment = comment_line\n else:\n comment += '\\n' + comment_line\n elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):\n # Appears to be a ENV setup line\n comps = line.split('=', 1)\n dat = {}\n dat['name'] = comps[0]\n dat['value'] = comps[1]\n ret['env'].append(dat)\n elif len(line.split(' ')) > 5:\n # Appears to be a standard cron line\n comps = line.split(' ')\n dat = {'minute': comps[0],\n 'hour': comps[1],\n 'daymonth': comps[2],\n 'month': comps[3],\n 'dayweek': comps[4],\n 'identifier': identifier,\n 'cmd': ' '.join(comps[5:]),\n 'comment': comment,\n 'commented': False}\n if commented_cron_job:\n dat['commented'] = True\n ret['crons'].append(dat)\n identifier = None\n comment = None\n commented_cron_job = False\n else:\n ret['pre'].append(line)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Work with cron
.. note::
Salt does not escape cron metacharacters automatically. You should
backslash-escape percent characters and any other metacharacters that might
be interpreted incorrectly by the shell.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import random
import logging
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.stringutils
from salt.ext import six
from salt.ext.six.moves import range
TAG = '# Lines below here are managed by Salt, do not edit\n'
SALT_CRON_IDENTIFIER = 'SALT_CRON_IDENTIFIER'
SALT_CRON_NO_IDENTIFIER = 'NO ID SET'
log = logging.getLogger(__name__)
def __virtual__():
if salt.utils.path.which('crontab'):
return True
else:
return (False, 'Cannot load cron module: crontab command not found')
def _ensure_string(val):
# Account for cases where the identifier is not a string
# which would cause to_unicode to fail.
if not isinstance(val, six.string_types):
val = str(val) # future lint: enable=blacklisted-function
try:
return salt.utils.stringutils.to_unicode(val)
except TypeError:
return ''
def _cron_id(cron):
'''SAFETYBELT, Only set if we really have an identifier'''
cid = None
if cron['identifier']:
cid = cron['identifier']
else:
cid = SALT_CRON_NO_IDENTIFIER
if cid:
return _ensure_string(cid)
def _cron_matched(cron, cmd, identifier=None):
'''Check if:
- we find a cron with same cmd, old state behavior
- but also be smart enough to remove states changed crons where we do
not removed priorly by a cron.absent by matching on the provided
identifier.
We assure retrocompatibility by only checking on identifier if
and only if an identifier was set on the serialized crontab
'''
ret, id_matched = False, None
cid = _cron_id(cron)
if cid:
if not identifier:
identifier = SALT_CRON_NO_IDENTIFIER
eidentifier = _ensure_string(identifier)
# old style second round
# after saving crontab, we must check that if
# we have not the same command, but the default id
# to not set that as a match
if (
cron.get('cmd', None) != cmd
and cid == SALT_CRON_NO_IDENTIFIER
and eidentifier == SALT_CRON_NO_IDENTIFIER
):
id_matched = False
else:
# on saving, be sure not to overwrite a cron
# with specific identifier but also track
# crons where command is the same
# but with the default if that we gonna overwrite
if (
cron.get('cmd', None) == cmd
and cid == SALT_CRON_NO_IDENTIFIER
and identifier
):
cid = eidentifier
id_matched = eidentifier == cid
if (
((id_matched is None) and cmd == cron.get('cmd', None))
or id_matched
):
ret = True
return ret
def _needs_change(old, new):
if old != new:
if new == 'random':
# Allow switch from '*' or not present to 'random'
if old == '*':
return True
elif new is not None:
return True
return False
def _render_tab(lst):
'''
Takes a tab list structure and renders it to a list for applying it to
a file
'''
ret = []
for pre in lst['pre']:
ret.append('{0}\n'.format(pre))
if ret:
if ret[-1] != TAG:
ret.append(TAG)
else:
ret.append(TAG)
for env in lst['env']:
if (env['value'] is None) or (env['value'] == ""):
ret.append('{0}=""\n'.format(env['name']))
else:
ret.append('{0}={1}\n'.format(env['name'], env['value']))
for cron in lst['crons']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2} {3} {4} {5} {6}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['minute'],
cron['hour'],
cron['daymonth'],
cron['month'],
cron['dayweek'],
cron['cmd']
)
)
for cron in lst['special']:
if cron['comment'] is not None or cron['identifier'] is not None:
comment = '#'
if cron['comment']:
comment += ' {0}'.format(
cron['comment'].rstrip().replace('\n', '\n# '))
if cron['identifier']:
comment += ' {0}:{1}'.format(SALT_CRON_IDENTIFIER,
cron['identifier'])
comment += '\n'
ret.append(comment)
ret.append('{0}{1} {2}\n'.format(
cron['commented'] is True and '#DISABLED#' or '',
cron['spec'],
cron['cmd']
)
)
return ret
def _get_cron_cmdstr(path, user=None):
'''
Returns a format string, to be used to build a crontab command.
'''
if user:
cmd = 'crontab -u {0}'.format(user)
else:
cmd = 'crontab'
return '{0} {1}'.format(cmd, path)
def _check_instance_uid_match(user):
'''
Returns true if running instance's UID matches the specified user UID
'''
return os.geteuid() == __salt__['file.user_to_uid'](user)
def write_cron_file(user, path):
'''
Writes the contents of a file to a user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.retcode'](_get_cron_cmdstr(path),
runas=user,
python_shell=False) == 0
else:
return __salt__['cmd.retcode'](_get_cron_cmdstr(path, user),
python_shell=False) == 0
def write_cron_file_verbose(user, path):
'''
Writes the contents of a file to a user's crontab and return error message on error
CLI Example:
.. code-block:: bash
salt '*' cron.write_cron_file_verbose root /tmp/new_cron
.. versionchanged:: 2015.8.9
.. note::
Some OS' do not support specifying user via the `crontab` command i.e. (Solaris, AIX)
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
return __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
return __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
def _write_cron_lines(user, lines):
'''
Takes a list of lines to be committed to a user's crontab and writes it
'''
lines = [salt.utils.stringutils.to_str(_l) for _l in lines]
path = salt.utils.files.mkstemp()
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
# In some cases crontab command should be executed as user rather than root
with salt.utils.files.fpopen(path, 'w+', uid=__salt__['file.user_to_uid'](user), mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path),
runas=user,
python_shell=False)
else:
with salt.utils.files.fpopen(path, 'w+', mode=0o600) as fp_:
fp_.writelines(lines)
ret = __salt__['cmd.run_all'](_get_cron_cmdstr(path, user),
python_shell=False)
os.remove(path)
return ret
def _date_time_match(cron, **kwargs):
'''
Returns true if the minute, hour, etc. params match their counterparts from
the dict returned from list_tab().
'''
return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
def raw_cron(user):
'''
Return the contents of the user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.raw_cron root
'''
if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'):
cmd = 'crontab -l'
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
runas=user,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
else:
cmd = 'crontab -u {0} -l'.format(user)
# Preserve line endings
lines = salt.utils.data.decode(
__salt__['cmd.run_stdout'](cmd,
ignore_retcode=True,
rstrip=False,
python_shell=False)
).splitlines(True)
if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'):
del lines[0:3]
return ''.join(lines)
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
comment = None
identifier = None
for line in data.splitlines():
if line == '# Lines below here are managed by Salt, do not edit':
flag = True
continue
if flag:
commented_cron_job = False
if line.startswith('#DISABLED#'):
# It's a commented cron job
line = line[10:]
commented_cron_job = True
if line.startswith('@'):
# Its a "special" line
dat = {}
comps = line.split()
if len(comps) < 2:
# Invalid line
continue
dat['spec'] = comps[0]
dat['cmd'] = ' '.join(comps[1:])
dat['identifier'] = identifier
dat['comment'] = comment
dat['commented'] = False
if commented_cron_job:
dat['commented'] = True
ret['special'].append(dat)
identifier = None
comment = None
commented_cron_job = False
elif line.startswith('#'):
# It's a comment! Catch it!
comment_line = line.lstrip('# ')
# load the identifier if any
if SALT_CRON_IDENTIFIER in comment_line:
parts = comment_line.split(SALT_CRON_IDENTIFIER)
comment_line = parts[0].rstrip()
# skip leading :
if len(parts[1]) > 1:
identifier = parts[1][1:]
if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('=', 1)
dat = {}
dat['name'] = comps[0]
dat['value'] = comps[1]
ret['env'].append(dat)
elif len(line.split(' ')) > 5:
# Appears to be a standard cron line
comps = line.split(' ')
dat = {'minute': comps[0],
'hour': comps[1],
'daymonth': comps[2],
'month': comps[3],
'dayweek': comps[4],
'identifier': identifier,
'cmd': ' '.join(comps[5:]),
'comment': comment,
'commented': False}
if commented_cron_job:
dat['commented'] = True
ret['crons'].append(dat)
identifier = None
comment = None
commented_cron_job = False
else:
ret['pre'].append(line)
return ret
# For consistency's sake
ls = salt.utils.functools.alias_function(list_tab, 'ls')
def get_entry(user, identifier=None, cmd=None):
'''
Return the specified entry from user's crontab.
identifier will be used if specified, otherwise will lookup cmd
Either identifier or cmd should be specified.
user:
User's crontab to query
identifier:
Search for line with identifier
cmd:
Search for cron line with cmd
CLI Example:
.. code-block:: bash
salt '*' cron.identifier_exists root identifier=task1
'''
cron_entries = list_tab(user).get('crons', False)
for cron_entry in cron_entries:
if identifier and cron_entry.get('identifier') == identifier:
return cron_entry
elif cmd and cron_entry.get('cmd') == cmd:
return cron_entry
return False
def set_special(user,
special,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Set up a special command in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_special root @hourly 'echo foobar'
'''
lst = list_tab(user)
for cron in lst['special']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['spec'], special)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_special(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['spec'], special):
special = cron['spec']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_special(user, special, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'spec': special,
'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
lst['special'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def _get_cron_date_time(**kwargs):
'''
Returns a dict of date/time values to be used in a cron entry
'''
# Define ranges (except daymonth, as it depends on the month)
range_max = {
'minute': list(list(range(60))),
'hour': list(list(range(24))),
'month': list(list(range(1, 13))),
'dayweek': list(list(range(7)))
}
ret = {}
for param in ('minute', 'hour', 'month', 'dayweek'):
value = six.text_type(kwargs.get(param, '1')).lower()
if value == 'random':
ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
elif len(value.split(':')) == 2:
cron_range = sorted(value.split(':'))
start, end = int(cron_range[0]), int(cron_range[1])
ret[param] = six.text_type(random.randint(start, end))
else:
ret[param] = value
if ret['month'] in '1 3 5 7 8 10 12'.split():
daymonth_max = 31
elif ret['month'] in '4 6 9 11'.split():
daymonth_max = 30
else:
# This catches both '2' and '*'
daymonth_max = 28
daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
if daymonth == 'random':
ret['daymonth'] = \
six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
else:
ret['daymonth'] = daymonth
return ret
def set_job(user,
minute,
hour,
daymonth,
month,
dayweek,
cmd,
commented=False,
comment=None,
identifier=None):
'''
Sets a cron job up for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.set_job root '*' '*' '*' '*' 1 /usr/local/weekly
'''
# Scrub the types
minute = six.text_type(minute).lower()
hour = six.text_type(hour).lower()
daymonth = six.text_type(daymonth).lower()
month = six.text_type(month).lower()
dayweek = six.text_type(dayweek).lower()
lst = list_tab(user)
for cron in lst['crons']:
cid = _cron_id(cron)
if _cron_matched(cron, cmd, identifier):
test_setted_id = (
cron['identifier'] is None
and SALT_CRON_NO_IDENTIFIER
or cron['identifier'])
tests = [(cron['comment'], comment),
(cron['commented'], commented),
(identifier, test_setted_id),
(cron['minute'], minute),
(cron['hour'], hour),
(cron['daymonth'], daymonth),
(cron['month'], month),
(cron['dayweek'], dayweek)]
if cid or identifier:
tests.append((cron['cmd'], cmd))
if any([_needs_change(x, y) for x, y in tests]):
rm_job(user, cmd, identifier=cid)
# Use old values when setting the new job if there was no
# change needed for a given parameter
if not _needs_change(cron['minute'], minute):
minute = cron['minute']
if not _needs_change(cron['hour'], hour):
hour = cron['hour']
if not _needs_change(cron['daymonth'], daymonth):
daymonth = cron['daymonth']
if not _needs_change(cron['month'], month):
month = cron['month']
if not _needs_change(cron['dayweek'], dayweek):
dayweek = cron['dayweek']
if not _needs_change(cron['commented'], commented):
commented = cron['commented']
if not _needs_change(cron['comment'], comment):
comment = cron['comment']
if not _needs_change(cron['cmd'], cmd):
cmd = cron['cmd']
if (
cid == SALT_CRON_NO_IDENTIFIER
):
if identifier:
cid = identifier
if (
cid == SALT_CRON_NO_IDENTIFIER
and cron['identifier'] is None
):
cid = None
cron['identifier'] = cid
if not cid or (
cid and not _needs_change(cid, identifier)
):
identifier = cid
jret = set_job(user, minute, hour, daymonth,
month, dayweek, cmd, commented=commented,
comment=comment, identifier=identifier)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
cron = {'cmd': cmd,
'identifier': identifier,
'comment': comment,
'commented': commented}
cron.update(_get_cron_date_time(minute=minute, hour=hour,
daymonth=daymonth, month=month,
dayweek=dayweek))
lst['crons'].append(cron)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
def rm_special(user, cmd, special=None, identifier=None):
'''
Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['special'])):
if rm_ is not None:
break
if _cron_matched(lst['special'][ind], cmd, identifier=identifier):
if special is None:
# No special param was specified
rm_ = ind
else:
if lst['special'][ind]['spec'] == special:
rm_ = ind
if rm_ is not None:
lst['special'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
def rm_job(user,
cmd,
minute=None,
hour=None,
daymonth=None,
month=None,
dayweek=None,
identifier=None):
'''
Remove a cron job for a specified user. If any of the day/time params are
specified, the job will only be removed if the specified params match.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_job root /usr/local/weekly
salt '*' cron.rm_job root /usr/bin/foo dayweek=1
'''
lst = list_tab(user)
ret = 'absent'
rm_ = None
for ind in range(len(lst['crons'])):
if rm_ is not None:
break
if _cron_matched(lst['crons'][ind], cmd, identifier=identifier):
if not any([x is not None
for x in (minute, hour, daymonth, month, dayweek)]):
# No date/time params were specified
rm_ = ind
else:
if _date_time_match(lst['crons'][ind],
minute=minute,
hour=hour,
daymonth=daymonth,
month=month,
dayweek=dayweek):
rm_ = ind
if rm_ is not None:
lst['crons'].pop(rm_)
ret = 'removed'
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return ret
rm = salt.utils.functools.alias_function(rm_job, 'rm')
def set_env(user, name, value=None):
'''
Set up an environment variable in the crontab.
CLI Example:
.. code-block:: bash
salt '*' cron.set_env root MAILTO user@example.com
'''
lst = list_tab(user)
for env in lst['env']:
if name == env['name']:
if value != env['value']:
rm_env(user, name)
jret = set_env(user, name, value)
if jret == 'new':
return 'updated'
else:
return jret
return 'present'
env = {'name': name, 'value': value}
lst['env'].append(env)
comdat = _write_cron_lines(user, _render_tab(lst))
if comdat['retcode']:
# Failed to commit, return the error
return comdat['stderr']
return 'new'
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
exists
|
python
|
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
|
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L103-L127
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
create
|
python
|
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L130-L177
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
delete
|
python
|
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L180-L204
|
[
"def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,\n keyid=None, profile=None):\n '''\n Delete all objects in a given S3 bucket.\n\n Returns {deleted: true} if all objects were deleted\n and {deleted: false, failed: [key, ...]} otherwise\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_s3_bucket.empty mybucket\n\n '''\n\n stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,\n profile=profile)\n Delete = {}\n Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]\n Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]\n if Delete['Objects']:\n ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,\n region=region, key=key, keyid=keyid, profile=profile)\n failed = ret.get('failed', [])\n if failed:\n return {'deleted': False, 'failed': ret[failed]}\n return {'deleted': True}\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
delete_objects
|
python
|
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
|
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L207-L249
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
describe
|
python
|
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
|
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L252-L315
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
empty
|
python
|
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
|
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L318-L345
|
[
"def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n Delete objects in a given S3 bucket.\n\n Returns {deleted: true} if all objects were deleted\n and {deleted: false, failed: [key, ...]} otherwise\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'\n\n '''\n\n if isinstance(Delete, six.string_types):\n Delete = salt.utils.json.loads(Delete)\n if not isinstance(Delete, dict):\n raise SaltInvocationError(\"Malformed Delete request.\")\n if 'Objects' not in Delete:\n raise SaltInvocationError(\"Malformed Delete request.\")\n\n failed = []\n objs = Delete['Objects']\n for i in range(0, len(objs), 1000):\n chunk = objs[i:i+1000]\n subset = {'Objects': chunk, 'Quiet': True}\n try:\n args = {'Bucket': Bucket}\n args.update({'MFA': MFA}) if MFA else None\n args.update({'RequestPayer': RequestPayer}) if RequestPayer else None\n args.update({'Delete': subset})\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n ret = conn.delete_objects(**args)\n failed += ret.get('Errors', [])\n except ClientError as e:\n return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}\n\n if failed:\n return {'deleted': False, 'failed': failed}\n else:\n return {'deleted': True}\n",
"def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n List objects in a given S3 bucket.\n\n Returns a list of objects.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion boto_s3_bucket.list_object_versions mybucket\n\n '''\n\n try:\n Versions = []\n DeleteMarkers = []\n args = {'Bucket': Bucket}\n args.update({'Delimiter': Delimiter}) if Delimiter else None\n args.update({'EncodingType': EncodingType}) if Delimiter else None\n args.update({'Prefix': Prefix}) if Prefix else None\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n IsTruncated = True\n while IsTruncated:\n ret = conn.list_object_versions(**args)\n IsTruncated = ret.get('IsTruncated', False)\n if IsTruncated in ('True', 'true', True):\n args['KeyMarker'] = ret['NextKeyMarker']\n args['VersionIdMarker'] = ret['NextVersionIdMarker']\n Versions += ret.get('Versions', [])\n DeleteMarkers += ret.get('DeleteMarkers', [])\n return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}\n except ClientError as e:\n return {'error': __utils__['boto3.get_error'](e)}\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
list
|
python
|
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
|
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L348-L373
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
list_object_versions
|
python
|
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
|
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L376-L410
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
list_objects
|
python
|
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
|
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L413-L446
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_acl
|
python
|
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L449-L491
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_cors
|
python
|
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L494-L524
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_lifecycle_configuration
|
python
|
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L527-L559
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_logging
|
python
|
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L562-L597
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_notification_configuration
|
python
|
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L600-L643
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_policy
|
python
|
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L646-L671
|
[
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_replication
|
python
|
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L688-L718
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n",
"def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):\n if name.startswith('arn:aws:iam:'):\n return name\n\n account_id = __salt__['boto_iam.get_account_id'](\n region=region, key=key, keyid=keyid, profile=profile\n )\n if profile and 'region' in profile:\n region = profile['region']\n if region is None:\n region = 'us-east-1'\n return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_request_payment
|
python
|
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L721-L744
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_tagging
|
python
|
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L747-L775
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_versioning
|
python
|
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L778-L807
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
put_website
|
python
|
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
|
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L810-L842
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n"
] |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
delete_cors
|
python
|
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L845-L866
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
delete_lifecycle_configuration
|
python
|
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L869-L890
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
delete_replication
|
python
|
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L917-L938
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
delete_tagging
|
python
|
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L941-L962
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/modules/boto_s3_bucket.py
|
delete_website
|
python
|
def delete_website(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_website(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
Remove the website configuration from the given bucket
Returns {deleted: true} if website configuration was deleted and returns
{deleted: False} if website configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_website my_bucket
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L965-L986
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon S3 Buckets
.. versionadded:: 2016.3.0
:depends:
- boto
- boto3
The dependencies listed above can be installed via package or pip.
:configuration: This module accepts explicit Lambda credentials but can also
utilize IAM roles assigned to the instance through Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API and no
further configuration is necessary. More Information available at:
.. code-block:: text
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file:
.. code-block:: yaml
s3.keyid: GKTADJGHEIQSXMKKRBJ08H
s3.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
s3.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
# disable complaints about perfectly valid non-assignment code
# pylint: disable=W0106
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error
import salt.utils.compat
import salt.utils.json
import salt.utils.versions
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
# pylint: disable=unused-import
import boto
import boto3
# pylint: enable=unused-import
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# pylint: enable=import-error
def __virtual__():
'''
Only load if boto libraries exist and if boto libraries are greater than
a given version.
'''
# the boto_lambda execution module relies on the connect_to_region() method
# which was added in boto 2.8.0
# https://github.com/boto/boto/commit/33ac26b416fbb48a60602542b4ce15dcc7029f12
return salt.utils.versions.check_boto_reqs(
boto3_ver='1.2.1'
)
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto3.assign_funcs'](__name__, 's3')
def exists(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, check to see if the given bucket exists.
Returns True if the given bucket exists and returns False if the given
bucket does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.exists mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.head_bucket(Bucket=Bucket)
return {'exists': True}
except ClientError as e:
if e.response.get('Error', {}).get('Code') == '404':
return {'exists': False}
err = __utils__['boto3.get_error'](e)
return {'error': err}
def create(Bucket,
ACL=None, LocationConstraint=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create an S3 Bucket.
Returns {created: true} if the bucket was created and returns
{created: False} if the bucket was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.create my_bucket \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"' \\
LocationConstraint=us-west-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('ACL', 'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
if LocationConstraint:
kwargs['CreateBucketConfiguration'] = {'LocationConstraint': LocationConstraint}
location = conn.create_bucket(Bucket=Bucket,
**kwargs)
conn.get_waiter("bucket_exists").wait(Bucket=Bucket)
if location:
log.info('The newly created bucket name is located at %s', location['Location'])
return {'created': True, 'name': Bucket, 'Location': location['Location']}
else:
log.warning('Bucket was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)}
def delete(Bucket, MFA=None, RequestPayer=None, Force=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name, delete it, optionally emptying it first.
Returns {deleted: true} if the bucket was deleted and returns
{deleted: false} if the bucket was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Force:
empty(Bucket, MFA=MFA, RequestPayer=RequestPayer, region=region,
key=key, keyid=keyid, profile=profile)
conn.delete_bucket(Bucket=Bucket)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
region=None, key=None, keyid=None, profile=None):
'''
Delete objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_objects mybucket '{Objects: [Key: myobject]}'
'''
if isinstance(Delete, six.string_types):
Delete = salt.utils.json.loads(Delete)
if not isinstance(Delete, dict):
raise SaltInvocationError("Malformed Delete request.")
if 'Objects' not in Delete:
raise SaltInvocationError("Malformed Delete request.")
failed = []
objs = Delete['Objects']
for i in range(0, len(objs), 1000):
chunk = objs[i:i+1000]
subset = {'Objects': chunk, 'Quiet': True}
try:
args = {'Bucket': Bucket}
args.update({'MFA': MFA}) if MFA else None
args.update({'RequestPayer': RequestPayer}) if RequestPayer else None
args.update({'Delete': subset})
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.delete_objects(**args)
failed += ret.get('Errors', [])
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
def describe(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Given a bucket name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.describe mybucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
result = {}
conn_dict = {'ACL': conn.get_bucket_acl,
'CORS': conn.get_bucket_cors,
'LifecycleConfiguration': conn.get_bucket_lifecycle_configuration,
'Location': conn.get_bucket_location,
'Logging': conn.get_bucket_logging,
'NotificationConfiguration': conn.get_bucket_notification_configuration,
'Policy': conn.get_bucket_policy,
'Replication': conn.get_bucket_replication,
'RequestPayment': conn.get_bucket_request_payment,
'Versioning': conn.get_bucket_versioning,
'Website': conn.get_bucket_website}
for key, query in six.iteritems(conn_dict):
try:
data = query(Bucket=Bucket)
except ClientError as e:
if e.response.get('Error', {}).get('Code') in (
'NoSuchLifecycleConfiguration',
'NoSuchCORSConfiguration',
'NoSuchBucketPolicy',
'NoSuchWebsiteConfiguration',
'ReplicationConfigurationNotFoundError',
'NoSuchTagSet',
):
continue
raise
if 'ResponseMetadata' in data:
del data['ResponseMetadata']
result[key] = data
tags = {}
try:
data = conn.get_bucket_tagging(Bucket=Bucket)
for tagdef in data.get('TagSet'):
tags[tagdef.get('Key')] = tagdef.get('Value')
except ClientError as e:
if not e.response.get('Error', {}).get('Code') == 'NoSuchTagSet':
raise
if tags:
result['Tagging'] = tags
return {'bucket': result}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'NoSuchBucket':
return {'bucket': None}
return {'error': __utils__['boto3.get_error'](e)}
def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
keyid=None, profile=None):
'''
Delete all objects in a given S3 bucket.
Returns {deleted: true} if all objects were deleted
and {deleted: false, failed: [key, ...]} otherwise
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.empty mybucket
'''
stuff = list_object_versions(Bucket, region=region, key=key, keyid=keyid,
profile=profile)
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
buckets = conn.list_buckets()
if not bool(buckets.get('Buckets')):
log.warning('No buckets found')
if 'ResponseMetadata' in buckets:
del buckets['ResponseMetadata']
return buckets
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket
'''
try:
Versions = []
DeleteMarkers = []
args = {'Bucket': Bucket}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_object_versions(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['KeyMarker'] = ret['NextKeyMarker']
args['VersionIdMarker'] = ret['NextVersionIdMarker']
Versions += ret.get('Versions', [])
DeleteMarkers += ret.get('DeleteMarkers', [])
return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def list_objects(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
FetchOwner=False, StartAfter=None, region=None, key=None,
keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_objects mybucket
'''
try:
Contents = []
args = {'Bucket': Bucket, 'FetchOwner': FetchOwner}
args.update({'Delimiter': Delimiter}) if Delimiter else None
args.update({'EncodingType': EncodingType}) if Delimiter else None
args.update({'Prefix': Prefix}) if Prefix else None
args.update({'StartAfter': StartAfter}) if StartAfter else None
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
IsTruncated = True
while IsTruncated:
ret = conn.list_objects_v2(**args)
IsTruncated = ret.get('IsTruncated', False)
if IsTruncated in ('True', 'true', True):
args['ContinuationToken'] = ret['NextContinuationToken']
Contents += ret.get('Contents', [])
return {'Contents': Contents}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)}
def put_acl(Bucket,
ACL=None,
AccessControlPolicy=None,
GrantFullControl=None,
GrantRead=None,
GrantReadACP=None,
GrantWrite=None,
GrantWriteACP=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the ACL for a bucket.
Returns {updated: true} if the ACL was updated and returns
{updated: False} if the ACL was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_acl my_bucket 'public' \\
GrantFullControl='emailaddress=example@example.com' \\
GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"' \\
GrantReadACP='emailaddress="exampl@example.com",id="2345678909876432"'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if AccessControlPolicy is not None:
if isinstance(AccessControlPolicy, six.string_types):
AccessControlPolicy = salt.utils.json.loads(AccessControlPolicy)
kwargs['AccessControlPolicy'] = AccessControlPolicy
for arg in ('ACL',
'GrantFullControl',
'GrantRead', 'GrantReadACP',
'GrantWrite', 'GrantWriteACP'):
if locals()[arg] is not None:
kwargs[arg] = str(locals()[arg]) # future lint: disable=blacklisted-function
conn.put_bucket_acl(Bucket=Bucket, **kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_cors(Bucket,
CORSRules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the CORS rules for a bucket.
Returns {updated: true} if CORS was updated and returns
{updated: False} if CORS was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_cors my_bucket '[{\\
"AllowedHeaders":[],\\
"AllowedMethods":["GET"],\\
"AllowedOrigins":["*"],\\
"ExposeHeaders":[],\\
"MaxAgeSeconds":123,\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if CORSRules is not None and isinstance(CORSRules, six.string_types):
CORSRules = salt.utils.json.loads(CORSRules)
conn.put_bucket_cors(Bucket=Bucket, CORSConfiguration={'CORSRules': CORSRules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_lifecycle_configuration(Bucket,
Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the Lifecycle rules for a bucket.
Returns {updated: true} if Lifecycle was updated and returns
{updated: False} if Lifecycle was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_lifecycle_configuration my_bucket '[{\\
"Expiration": {...},\\
"ID": "idstring",\\
"Prefix": "prefixstring",\\
"Status": "enabled",\\
"Transitions": [{...},],\\
"NoncurrentVersionTransitions": [{...},],\\
"NoncurrentVersionExpiration": {...},\\
}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Rules is not None and isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_lifecycle_configuration(Bucket=Bucket, LifecycleConfiguration={'Rules': Rules})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_logging(Bucket,
TargetBucket=None, TargetPrefix=None, TargetGrants=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the logging parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
logstate = {}
targets = {'TargetBucket': TargetBucket,
'TargetGrants': TargetGrants,
'TargetPrefix': TargetPrefix}
for key, val in six.iteritems(targets):
if val is not None:
logstate[key] = val
if logstate:
logstatus = {'LoggingEnabled': logstate}
else:
logstatus = {}
if TargetGrants is not None and isinstance(TargetGrants, six.string_types):
TargetGrants = salt.utils.json.loads(TargetGrants)
conn.put_bucket_logging(Bucket=Bucket, BucketLoggingStatus=logstatus)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_notification_configuration(Bucket,
TopicConfigurations=None, QueueConfigurations=None,
LambdaFunctionConfigurations=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the notification parameters for a bucket.
Returns {updated: true} if parameters were updated and returns
{updated: False} if parameters were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_notification_configuration my_bucket
[{...}] \\
[{...}] \\
[{...}]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if TopicConfigurations is None:
TopicConfigurations = []
elif isinstance(TopicConfigurations, six.string_types):
TopicConfigurations = salt.utils.json.loads(TopicConfigurations)
if QueueConfigurations is None:
QueueConfigurations = []
elif isinstance(QueueConfigurations, six.string_types):
QueueConfigurations = salt.utils.json.loads(QueueConfigurations)
if LambdaFunctionConfigurations is None:
LambdaFunctionConfigurations = []
elif isinstance(LambdaFunctionConfigurations, six.string_types):
LambdaFunctionConfigurations = salt.utils.json.loads(LambdaFunctionConfigurations)
# TODO allow the user to use simple names & substitute ARNs for those names
conn.put_bucket_notification_configuration(Bucket=Bucket, NotificationConfiguration={
'TopicConfigurations': TopicConfigurations,
'QueueConfigurations': QueueConfigurations,
'LambdaFunctionConfigurations': LambdaFunctionConfigurations,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if Policy is None:
Policy = '{}'
elif not isinstance(Policy, six.string_types):
Policy = salt.utils.json.dumps(Policy)
conn.put_bucket_policy(Bucket=Bucket, Policy=Policy)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def _get_role_arn(name, region=None, key=None, keyid=None, profile=None):
if name.startswith('arn:aws:iam:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
if profile and 'region' in profile:
region = profile['region']
if region is None:
region = 'us-east-1'
return 'arn:aws:iam::{0}:role/{1}'.format(account_id, name)
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Role = _get_role_arn(name=Role,
region=region, key=key, keyid=keyid, profile=profile)
if Rules is None:
Rules = []
elif isinstance(Rules, six.string_types):
Rules = salt.utils.json.loads(Rules)
conn.put_bucket_replication(Bucket=Bucket, ReplicationConfiguration={
'Role': Role,
'Rules': Rules
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_request_payment(Bucket, Payer,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the request payment configuration for a bucket.
Returns {updated: true} if request payment configuration was updated and returns
{updated: False} if request payment configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_request_payment my_bucket Requester
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.put_bucket_request_payment(Bucket=Bucket, RequestPaymentConfiguration={
'Payer': Payer,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_tagging my_bucket my_role [...]
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.put_bucket_tagging(Bucket=Bucket, Tagging={
'TagSet': tagslist,
})
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_versioning(Bucket, Status, MFADelete=None, MFA=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the versioning configuration for a bucket.
Returns {updated: true} if versioning configuration was updated and returns
{updated: False} if versioning configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_versioning my_bucket Enabled
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
VersioningConfiguration = {'Status': Status}
if MFADelete is not None:
VersioningConfiguration['MFADelete'] = MFADelete
kwargs = {}
if MFA is not None:
kwargs['MFA'] = MFA
conn.put_bucket_versioning(Bucket=Bucket,
VersioningConfiguration=VersioningConfiguration,
**kwargs)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def put_website(Bucket, ErrorDocument=None, IndexDocument=None,
RedirectAllRequestsTo=None, RoutingRules=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the website configuration for a bucket.
Returns {updated: true} if website configuration was updated and returns
{updated: False} if website configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_website my_bucket IndexDocument='{"Suffix":"index.html"}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
WebsiteConfiguration = {}
for key in ('ErrorDocument', 'IndexDocument',
'RedirectAllRequestsTo', 'RoutingRules'):
val = locals()[key]
if val is not None:
if isinstance(val, six.string_types):
WebsiteConfiguration[key] = salt.utils.json.loads(val)
else:
WebsiteConfiguration[key] = val
conn.put_bucket_website(Bucket=Bucket,
WebsiteConfiguration=WebsiteConfiguration)
return {'updated': True, 'name': Bucket}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
def delete_cors(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the CORS configuration for the given bucket
Returns {deleted: true} if CORS was deleted and returns
{deleted: False} if CORS was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_cors my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_cors(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_lifecycle_configuration(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the lifecycle configuration for the given bucket
Returns {deleted: true} if Lifecycle was deleted and returns
{deleted: False} if Lifecycle was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_lifecycle_configuration my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_lifecycle(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_policy(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the policy from the given bucket
Returns {deleted: true} if policy was deleted and returns
{deleted: False} if policy was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_policy my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_policy(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_replication my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_replication(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
def delete_tagging(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the tags from the given bucket
Returns {deleted: true} if tags were deleted and returns
{deleted: False} if tags were not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.delete_tagging my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_bucket_tagging(Bucket=Bucket)
return {'deleted': True, 'name': Bucket}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
|
saltstack/salt
|
salt/acl/__init__.py
|
PublisherACL.user_is_blacklisted
|
python
|
def user_is_blacklisted(self, user):
'''
Takes a username as a string and returns a boolean. True indicates that
the provided user has been blacklisted
'''
return not salt.utils.stringutils.check_whitelist_blacklist(user, blacklist=self.blacklist.get('users', []))
|
Takes a username as a string and returns a boolean. True indicates that
the provided user has been blacklisted
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/acl/__init__.py#L29-L34
| null |
class PublisherACL(object):
'''
Represents the publisher ACL and provides methods
to query the ACL for given operations
'''
def __init__(self, blacklist):
self.blacklist = blacklist
def cmd_is_blacklisted(self, cmd):
# If this is a regular command, it is a single function
if isinstance(cmd, six.string_types):
cmd = [cmd]
for fun in cmd:
if not salt.utils.stringutils.check_whitelist_blacklist(fun, blacklist=self.blacklist.get('modules', [])):
return True
return False
def user_is_whitelisted(self, user):
return salt.utils.stringutils.check_whitelist_blacklist(user, whitelist=self.blacklist.get('users', []))
def cmd_is_whitelisted(self, cmd):
# If this is a regular command, it is a single function
if isinstance(cmd, str):
cmd = [cmd]
for fun in cmd:
if salt.utils.stringutils.check_whitelist_blacklist(fun, whitelist=self.blacklist.get('modules', [])):
return True
return False
|
saltstack/salt
|
salt/states/pagerduty_escalation_policy.py
|
present
|
python
|
def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a pagerduty escalation policy exists. Will create or update as needed.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/escalation_policies/create.
In addition, user and schedule id's will be translated from name (or email address)
into PagerDuty unique ids. For example:
.. code-block:: yaml
pagerduty_escalation_policy.present:
- name: bruce test escalation policy
- escalation_rules:
- targets:
- type: schedule
id: 'bruce test schedule level1'
- type: user
id: 'Bruce Sherrod'
In this example, 'Bruce Sherrod' will be looked up and replaced with the
PagerDuty id (usually a 7 digit all-caps string, e.g. PX6GQL7)
'''
# for convenience, we accept id, name, or email for users
# and we accept the id or name for schedules
for escalation_rule in kwargs['escalation_rules']:
for target in escalation_rule['targets']:
target_id = None
if target['type'] == 'user':
user = __salt__['pagerduty_util.get_resource']('users',
target['id'],
['email', 'name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if user:
target_id = user['id']
elif target['type'] == 'schedule':
schedule = __salt__['pagerduty_util.get_resource']('schedules',
target['id'],
['name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if schedule:
target_id = schedule['schedule']['id']
if target_id is None:
raise Exception('unidentified target: {0}'.format(target))
target['id'] = target_id
r = __salt__['pagerduty_util.resource_present']('escalation_policies',
['name', 'id'],
_diff,
profile,
subdomain,
api_key,
**kwargs)
return r
|
Ensure that a pagerduty escalation policy exists. Will create or update as needed.
This method accepts as args everything defined in
https://developer.pagerduty.com/documentation/rest/escalation_policies/create.
In addition, user and schedule id's will be translated from name (or email address)
into PagerDuty unique ids. For example:
.. code-block:: yaml
pagerduty_escalation_policy.present:
- name: bruce test escalation policy
- escalation_rules:
- targets:
- type: schedule
id: 'bruce test schedule level1'
- type: user
id: 'Bruce Sherrod'
In this example, 'Bruce Sherrod' will be looked up and replaced with the
PagerDuty id (usually a 7 digit all-caps string, e.g. PX6GQL7)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_escalation_policy.py#L49-L107
| null |
# -*- coding: utf-8 -*-
'''
Manage PagerDuty escalation policies.
Schedules and users can be referenced by pagerduty ID, or by name, or by email address.
For example:
.. code-block:: yaml
ensure test escalation policy:
pagerduty_escalation_policy.present:
- name: bruce test escalation policy
- escalation_rules:
- targets:
- type: schedule
id: 'bruce test schedule level1'
- type: user
id: 'Bruce Sherrod'
escalation_delay_in_minutes: 15
- targets:
- type: schedule
id: 'bruce test schedule level2'
escalation_delay_in_minutes: 15
- targets:
- type: user
id: 'Bruce TestUser1'
- type: user
id: 'Bruce TestUser2'
- type: user
id: 'Bruce TestUser3'
- type: user
id: 'bruce+test4@lyft.com'
escalation_delay_in_minutes: 15
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only load if the pygerduty module is available in __salt__
'''
return 'pagerduty_escalation_policy' if 'pagerduty_util.get_resource' in __salt__ else False
def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure that a PagerDuty escalation policy does not exist.
Accepts all the arguments that pagerduty_escalation_policy.present accepts;
but ignores all arguments except the name.
Name can be the escalation policy id or the escalation policy name.
'''
r = __salt__['pagerduty_util.resource_absent']('escalation_policies',
['name', 'id'],
profile,
subdomain,
api_key,
**kwargs)
return r
def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
objects_differ = None
for k, v in state_data.items():
if k == 'escalation_rules':
v = _escalation_rules_to_string(v)
resource_value = _escalation_rules_to_string(resource_object[k])
else:
if k not in resource_object.keys():
objects_differ = True
else:
resource_value = resource_object[k]
if v != resource_value:
objects_differ = '{0} {1} {2}'.format(k, v, resource_value)
break
if objects_differ:
return state_data
else:
return {}
def _escalation_rules_to_string(escalation_rules):
'convert escalation_rules dict to a string for comparison'
result = ''
for rule in escalation_rules:
result += 'escalation_delay_in_minutes: {0} '.format(rule['escalation_delay_in_minutes'])
for target in rule['targets']:
result += '{0}:{1} '.format(target['type'], target['id'])
return result
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.