repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/modules/mac_softwareupdate.py
update
def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name)
python
def update(name): ''' Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) cmd = ['softwareupdate', '--install', name] salt.utils.mac_utils.execute_return_success(cmd) return not update_available(name)
[ "def", "update", "(", "name", ")", ":", "if", "not", "update_available", "(", "name", ")", ":", "raise", "SaltInvocationError", "(", "'Update not available: {0}'", ".", "format", "(", "name", ")", ")", "cmd", "=", "[", "'softwareupdate'", ",", "'--install'", ...
Install a named update. :param str name: The name of the of the update to install. :return: True if successfully updated, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.update <update-name>
[ "Install", "a", "named", "update", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L276-L297
train
saltstack/salt
salt/modules/mac_softwareupdate.py
list_downloads
def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret
python
def list_downloads(): ''' Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads ''' outfiles = [] for root, subFolder, files in salt.utils.path.os_walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.files.fopen(f) as fhr: if update.rsplit('-', 1)[0] in salt.utils.stringutils.to_unicode(fhr.read()): ret.append(update) return ret
[ "def", "list_downloads", "(", ")", ":", "outfiles", "=", "[", "]", "for", "root", ",", "subFolder", ",", "files", "in", "salt", ".", "utils", ".", "path", ".", "os_walk", "(", "'/Library/Updates'", ")", ":", "for", "f", "in", "files", ":", "outfiles", ...
Return a list of all updates that have been downloaded locally. :return: A list of updates that have been downloaded :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.list_downloads
[ "Return", "a", "list", "of", "all", "updates", "that", "have", "been", "downloaded", "locally", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L319-L349
train
saltstack/salt
salt/modules/mac_softwareupdate.py
download
def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads()
python
def download(name): ''' Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name> ''' if not update_available(name): raise SaltInvocationError('Update not available: {0}'.format(name)) if name in list_downloads(): return True cmd = ['softwareupdate', '--download', name] salt.utils.mac_utils.execute_return_success(cmd) return name in list_downloads()
[ "def", "download", "(", "name", ")", ":", "if", "not", "update_available", "(", "name", ")", ":", "raise", "SaltInvocationError", "(", "'Update not available: {0}'", ".", "format", "(", "name", ")", ")", "if", "name", "in", "list_downloads", "(", ")", ":", ...
Download a named update so that it can be installed later with the ``update`` or ``update_all`` functions :param str name: The update to download. :return: True if successful, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdate.download <update name>
[ "Download", "a", "named", "update", "so", "that", "it", "can", "be", "installed", "later", "with", "the", "update", "or", "update_all", "functions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L352-L377
train
saltstack/salt
salt/modules/mac_softwareupdate.py
download_all
def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads()
python
def download_all(recommended=False, restart=True): ''' Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all ''' to_download = _get_available(recommended, restart) for name in to_download: download(name) return list_downloads()
[ "def", "download_all", "(", "recommended", "=", "False", ",", "restart", "=", "True", ")", ":", "to_download", "=", "_get_available", "(", "recommended", ",", "restart", ")", "for", "name", "in", "to_download", ":", "download", "(", "name", ")", "return", ...
Download all available updates so that they can be installed later with the ``update`` or ``update_all`` functions. It returns a list of updates that are now downloaded. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are installed. :param bool restart: Set this to False if you do not want to install updates that require a restart. Default is True :return: A list containing all downloaded updates on the system. :rtype: list CLI Example: .. code-block:: bash salt '*' softwareupdate.download_all
[ "Download", "all", "available", "updates", "so", "that", "they", "can", "be", "installed", "later", "with", "the", "update", "or", "update_all", "functions", ".", "It", "returns", "a", "list", "of", "updates", "that", "are", "now", "downloaded", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L380-L406
train
saltstack/salt
salt/modules/mac_softwareupdate.py
get_catalog
def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default'
python
def get_catalog(): ''' .. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.SoftwareUpdate.plist'] out = salt.utils.mac_utils.execute_return_result(cmd) if 'AppleCatalogURL' in out: cmd.append('AppleCatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out elif 'CatalogURL' in out: cmd.append('CatalogURL') out = salt.utils.mac_utils.execute_return_result(cmd) return out else: return 'Default'
[ "def", "get_catalog", "(", ")", ":", "cmd", "=", "[", "'defaults'", ",", "'read'", ",", "'/Library/Preferences/com.apple.SoftwareUpdate.plist'", "]", "out", "=", "salt", ".", "utils", ".", "mac_utils", ".", "execute_return_result", "(", "cmd", ")", "if", "'Apple...
.. versionadded:: 2016.3.0 Get the current catalog being used for update lookups. Will return a url if a custom catalog has been specified. Otherwise the word 'Default' will be returned :return: The catalog being used for update lookups :rtype: str CLI Example: .. code-block:: bash salt '*' softwareupdates.get_catalog
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L409-L440
train
saltstack/salt
salt/modules/mac_softwareupdate.py
set_catalog
def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url
python
def set_catalog(url): ''' .. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns the passed url cmd = ['softwareupdate', '--set-catalog', url] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == url
[ "def", "set_catalog", "(", "url", ")", ":", "# This command always returns an error code, though it completes", "# successfully. Success will be determined by making sure get_catalog", "# returns the passed url", "cmd", "=", "[", "'softwareupdate'", ",", "'--set-catalog'", ",", "url"...
.. versionadded:: 2016.3.0 Set the Software Update Catalog to the URL specified :param str url: The url to the update catalog :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.set_catalog http://swupd.local:8888/index.sucatalog
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L443-L470
train
saltstack/salt
salt/modules/mac_softwareupdate.py
reset_catalog
def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
python
def reset_catalog(): ''' .. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog ''' # This command always returns an error code, though it completes # successfully. Success will be determined by making sure get_catalog # returns 'Default' cmd = ['softwareupdate', '--clear-catalog'] try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: pass return get_catalog() == 'Default'
[ "def", "reset_catalog", "(", ")", ":", "# This command always returns an error code, though it completes", "# successfully. Success will be determined by making sure get_catalog", "# returns 'Default'", "cmd", "=", "[", "'softwareupdate'", ",", "'--clear-catalog'", "]", "try", ":", ...
.. versionadded:: 2016.3.0 Reset the Software Update Catalog to the default. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' softwareupdates.reset_catalog
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_softwareupdate.py#L473-L498
train
saltstack/salt
salt/modules/etcd_mod.py
get_
def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) if recurse: return client.tree(key) else: return client.get(key, recurse=recurse)
python
def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) if recurse: return client.tree(key) else: return client.get(key, recurse=recurse)
[ "def", "get_", "(", "key", ",", "recurse", "=", "False", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "__utils__", "[", "'etcd_util.get_conn'", "]", "(", "__opts__", ",", "profile", ",", "*", "*", "kwargs", ")", "if"...
.. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=my_etcd_config salt myminion etcd.get /path/to/key host=127.0.0.1 port=2379
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L76-L95
train
saltstack/salt
salt/modules/etcd_mod.py
set_
def set_(key, value, profile=None, ttl=None, directory=False, **kwargs): ''' .. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.set(key, value, ttl=ttl, directory=directory)
python
def set_(key, value, profile=None, ttl=None, directory=False, **kwargs): ''' .. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.set(key, value, ttl=ttl, directory=directory)
[ "def", "set_", "(", "key", ",", "value", ",", "profile", "=", "None", ",", "ttl", "=", "None", ",", "directory", "=", "False", ",", "*", "*", "kwargs", ")", ":", "client", "=", "__utils__", "[", "'etcd_util.get_conn'", "]", "(", "__opts__", ",", "pro...
.. versionadded:: 2014.7.0 Set a key in etcd by direct path. Optionally, create a directory or set a TTL on the key. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.set /path/to/key value salt myminion etcd.set /path/to/key value profile=my_etcd_config salt myminion etcd.set /path/to/key value host=127.0.0.1 port=2379 salt myminion etcd.set /path/to/dir '' directory=True salt myminion etcd.set /path/to/key value ttl=5
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L98-L117
train
saltstack/salt
salt/modules/etcd_mod.py
update
def update(fields, path='', profile=None, **kwargs): ''' .. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root' ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.update(fields, path)
python
def update(fields, path='', profile=None, **kwargs): ''' .. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root' ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.update(fields, path)
[ "def", "update", "(", "fields", ",", "path", "=", "''", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "__utils__", "[", "'etcd_util.get_conn'", "]", "(", "__opts__", ",", "profile", ",", "*", "*", "kwargs", ")", "retu...
.. versionadded:: 2016.3.0 Sets a dictionary of values in one call. Useful for large updates in syndic environments. The dictionary can contain a mix of formats such as: .. code-block:: python { '/some/example/key': 'bar', '/another/example/key': 'baz' } Or it may be a straight dictionary, which will be flattened to look like the above format: .. code-block:: python { 'some': { 'example': { 'key': 'bar' } }, 'another': { 'example': { 'key': 'baz' } } } You can even mix the two formats and it will be flattened to the first format. Leading and trailing '/' will be removed. Empty directories can be created by setting the value of the key to an empty dictionary. The 'path' parameter will optionally set the root of the path to use. CLI Example: .. code-block:: bash salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" profile=my_etcd_config salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" host=127.0.0.1 port=2379 salt myminion etcd.update "{'/path/to/key': 'baz', '/another/key': 'bar'}" path='/some/root'
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L120-L171
train
saltstack/salt
salt/modules/etcd_mod.py
watch
def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.watch(key, recurse=recurse, timeout=timeout, index=index)
python
def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.watch(key, recurse=recurse, timeout=timeout, index=index)
[ "def", "watch", "(", "key", ",", "recurse", "=", "False", ",", "profile", "=", "None", ",", "timeout", "=", "0", ",", "index", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "__utils__", "[", "'etcd_util.get_conn'", "]", "(", "__opts_...
.. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key changed or not, the path to the key that changed and whether it is a directory or not. If something catastrophic happens, returns {} CLI Example: .. code-block:: bash salt myminion etcd.watch /path/to/key salt myminion etcd.watch /path/to/key timeout=10 salt myminion etcd.watch /patch/to/key profile=my_etcd_config index=10 salt myminion etcd.watch /patch/to/key host=127.0.0.1 port=2379
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L174-L196
train
saltstack/salt
salt/modules/etcd_mod.py
ls_
def ls_(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.ls(path)
python
def ls_(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379 ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.ls(path)
[ "def", "ls_", "(", "path", "=", "'/'", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "__utils__", "[", "'etcd_util.get_conn'", "]", "(", "__opts__", ",", "profile", ",", "*", "*", "kwargs", ")", "return", "client", "....
.. versionadded:: 2014.7.0 Return all keys and dirs inside a specific path. Returns an empty dict on failure. CLI Example: .. code-block:: bash salt myminion etcd.ls /path/to/dir/ salt myminion etcd.ls /path/to/dir/ profile=my_etcd_config salt myminion etcd.ls /path/to/dir/ host=127.0.0.1 port=2379
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L199-L216
train
saltstack/salt
salt/modules/etcd_mod.py
rm_
def rm_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.rm(key, recurse=recurse)
python
def rm_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.rm(key, recurse=recurse)
[ "def", "rm_", "(", "key", ",", "recurse", "=", "False", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "__utils__", "[", "'etcd_util.get_conn'", "]", "(", "__opts__", ",", "profile", ",", "*", "*", "kwargs", ")", "retu...
.. versionadded:: 2014.7.0 Delete a key from etcd. Returns True if the key was deleted, False if it was not and None if there was a failure. CLI Example: .. code-block:: bash salt myminion etcd.rm /path/to/key salt myminion etcd.rm /path/to/key profile=my_etcd_config salt myminion etcd.rm /path/to/key host=127.0.0.1 port=2379 salt myminion etcd.rm /path/to/dir recurse=True profile=my_etcd_config
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L219-L237
train
saltstack/salt
salt/modules/etcd_mod.py
tree
def tree(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.tree(path)
python
def tree(path='/', profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config ''' client = __utils__['etcd_util.get_conn'](__opts__, profile, **kwargs) return client.tree(path)
[ "def", "tree", "(", "path", "=", "'/'", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "__utils__", "[", "'etcd_util.get_conn'", "]", "(", "__opts__", ",", "profile", ",", "*", "*", "kwargs", ")", "return", "client", "...
.. versionadded:: 2014.7.0 Recurse through etcd and return all values. Returns None on failure. CLI Example: .. code-block:: bash salt myminion etcd.tree salt myminion etcd.tree profile=my_etcd_config salt myminion etcd.tree host=127.0.0.1 port=2379 salt myminion etcd.tree /path/to/keys profile=my_etcd_config
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/etcd_mod.py#L240-L257
train
saltstack/salt
salt/utils/aws.py
creds
def creds(provider): ''' Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead. ''' # Declare globals global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__ ret_credentials = () # if id or key is 'use-instance-role-credentials', pull them from meta-data ## if needed if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE: # Check to see if we have cache credentials that are still good if __Expiration__ != '': timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp < __Expiration__: # Current timestamp less than expiration fo cached credentials return __AccessKeyId__, __SecretAccessKey__, __Token__ # We don't have any cached credentials, or they are expired, get them # Connections to instance meta-data must fail fast and never be proxied try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() role = result.text except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}".format(role), proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' data = result.json() __AccessKeyId__ = data['AccessKeyId'] __SecretAccessKey__ = data['SecretAccessKey'] __Token__ = data['Token'] __Expiration__ = data['Expiration'] ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__ else: ret_credentials = provider['id'], provider['key'], '' if provider.get('role_arn') is not None: provider_shadow = provider.copy() provider_shadow.pop("role_arn", None) log.info("Assuming the role: %s", provider.get('role_arn')) ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1') return ret_credentials
python
def creds(provider): ''' Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead. ''' # Declare globals global __AccessKeyId__, __SecretAccessKey__, __Token__, __Expiration__ ret_credentials = () # if id or key is 'use-instance-role-credentials', pull them from meta-data ## if needed if provider['id'] == IROLE_CODE or provider['key'] == IROLE_CODE: # Check to see if we have cache credentials that are still good if __Expiration__ != '': timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp < __Expiration__: # Current timestamp less than expiration fo cached credentials return __AccessKeyId__, __SecretAccessKey__, __Token__ # We don't have any cached credentials, or they are expired, get them # Connections to instance meta-data must fail fast and never be proxied try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() role = result.text except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' try: result = requests.get( "http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}".format(role), proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) result.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError): return provider['id'], provider['key'], '' data = result.json() __AccessKeyId__ = data['AccessKeyId'] __SecretAccessKey__ = data['SecretAccessKey'] __Token__ = data['Token'] __Expiration__ = data['Expiration'] ret_credentials = __AccessKeyId__, __SecretAccessKey__, __Token__ else: ret_credentials = provider['id'], provider['key'], '' if provider.get('role_arn') is not None: provider_shadow = provider.copy() provider_shadow.pop("role_arn", None) log.info("Assuming the role: %s", provider.get('role_arn')) ret_credentials = assumed_creds(provider_shadow, role_arn=provider.get('role_arn'), location='us-east-1') return ret_credentials
[ "def", "creds", "(", "provider", ")", ":", "# Declare globals", "global", "__AccessKeyId__", ",", "__SecretAccessKey__", ",", "__Token__", ",", "__Expiration__", "ret_credentials", "=", "(", ")", "# if id or key is 'use-instance-role-credentials', pull them from meta-data", "...
Return the credentials for AWS signing. This could be just the id and key specified in the provider configuration, or if the id or key is set to the literal string 'use-instance-role-credentials' creds will pull the instance role credentials from the meta data, cache them, and provide them instead.
[ "Return", "the", "credentials", "for", "AWS", "signing", ".", "This", "could", "be", "just", "the", "id", "and", "key", "specified", "in", "the", "provider", "configuration", "or", "if", "the", "id", "or", "key", "is", "set", "to", "the", "literal", "str...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L81-L141
train
saltstack/salt
salt/utils/aws.py
sig2
def sig2(method, endpoint, params, provider, aws_api_version): ''' Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html ''' timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') # Retrieve access credentials from meta-data, or use provided access_key_id, secret_access_key, token = creds(provider) params_with_headers = params.copy() params_with_headers['AWSAccessKeyId'] = access_key_id params_with_headers['SignatureVersion'] = '2' params_with_headers['SignatureMethod'] = 'HmacSHA256' params_with_headers['Timestamp'] = '{0}'.format(timestamp) params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(list(map(params_with_headers.get, keys))) querystring = urlencode(list(zip(keys, values))) canonical = '{0}\n{1}\n/\n{2}'.format( method.encode('utf-8'), endpoint.encode('utf-8'), querystring.encode('utf-8'), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) sig = binascii.b2a_base64(hashed.digest()) params_with_headers['Signature'] = sig.strip() # Add in security token if we have one if token != '': params_with_headers['SecurityToken'] = token return params_with_headers
python
def sig2(method, endpoint, params, provider, aws_api_version): ''' Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html ''' timenow = datetime.utcnow() timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ') # Retrieve access credentials from meta-data, or use provided access_key_id, secret_access_key, token = creds(provider) params_with_headers = params.copy() params_with_headers['AWSAccessKeyId'] = access_key_id params_with_headers['SignatureVersion'] = '2' params_with_headers['SignatureMethod'] = 'HmacSHA256' params_with_headers['Timestamp'] = '{0}'.format(timestamp) params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(list(map(params_with_headers.get, keys))) querystring = urlencode(list(zip(keys, values))) canonical = '{0}\n{1}\n/\n{2}'.format( method.encode('utf-8'), endpoint.encode('utf-8'), querystring.encode('utf-8'), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) sig = binascii.b2a_base64(hashed.digest()) params_with_headers['Signature'] = sig.strip() # Add in security token if we have one if token != '': params_with_headers['SecurityToken'] = token return params_with_headers
[ "def", "sig2", "(", "method", ",", "endpoint", ",", "params", ",", "provider", ",", "aws_api_version", ")", ":", "timenow", "=", "datetime", ".", "utcnow", "(", ")", "timestamp", "=", "timenow", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "# Retrieve ...
Sign a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
[ "Sign", "a", "query", "against", "AWS", "services", "using", "Signature", "Version", "2", "Signing", "Process", ".", "This", "is", "documented", "at", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L144-L181
train
saltstack/salt
salt/utils/aws.py
sig4
def sig4(method, endpoint, params, prov_dict, aws_api_version=DEFAULT_AWS_API_VERSION, location=None, product='ec2', uri='/', requesturl=None, data='', headers=None, role_arn=None, payload_hash=None): ''' Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html ''' timenow = datetime.utcnow() # Retrieve access credentials from meta-data, or use provided if role_arn is None: access_key_id, secret_access_key, token = creds(prov_dict) else: access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location) if location is None: location = get_region_from_metadata() if location is None: location = DEFAULT_LOCATION params_with_headers = params.copy() if product not in ('s3', 'ssm'): params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(map(params_with_headers.get, keys)) querystring = urlencode(list(zip(keys, values))).replace('+', '%20') amzdate = timenow.strftime('%Y%m%dT%H%M%SZ') datestamp = timenow.strftime('%Y%m%d') new_headers = {} if isinstance(headers, dict): new_headers = headers.copy() # Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (''). if not payload_hash: payload_hash = salt.utils.hashutils.sha256_digest(data) new_headers['X-Amz-date'] = amzdate new_headers['host'] = endpoint new_headers['x-amz-content-sha256'] = payload_hash a_canonical_headers = [] a_signed_headers = [] if token != '': new_headers['X-Amz-security-token'] = token for header in sorted(new_headers.keys(), key=six.text_type.lower): lower_header = header.lower() a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip())) a_signed_headers.append(lower_header) canonical_headers = '\n'.join(a_canonical_headers) + '\n' signed_headers = ';'.join(a_signed_headers) algorithm = 'AWS4-HMAC-SHA256' # Combine elements to create create canonical request canonical_request = '\n'.join(( method, uri, querystring, canonical_headers, signed_headers, payload_hash )) # Create the string to sign credential_scope = '/'.join((datestamp, location, product, 'aws4_request')) string_to_sign = '\n'.join(( algorithm, amzdate, credential_scope, salt.utils.hashutils.sha256_digest(canonical_request) )) # Create the signing key using the function defined above. signing_key = _sig_key( secret_access_key, datestamp, location, product ) # Sign the string_to_sign using the signing_key signature = hmac.new( signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() # Add signing information to the request authorization_header = ( '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}' ).format( algorithm, access_key_id, credential_scope, signed_headers, signature, ) new_headers['Authorization'] = authorization_header requesturl = '{0}?{1}'.format(requesturl, querystring) return new_headers, requesturl
python
def sig4(method, endpoint, params, prov_dict, aws_api_version=DEFAULT_AWS_API_VERSION, location=None, product='ec2', uri='/', requesturl=None, data='', headers=None, role_arn=None, payload_hash=None): ''' Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html ''' timenow = datetime.utcnow() # Retrieve access credentials from meta-data, or use provided if role_arn is None: access_key_id, secret_access_key, token = creds(prov_dict) else: access_key_id, secret_access_key, token = assumed_creds(prov_dict, role_arn, location=location) if location is None: location = get_region_from_metadata() if location is None: location = DEFAULT_LOCATION params_with_headers = params.copy() if product not in ('s3', 'ssm'): params_with_headers['Version'] = aws_api_version keys = sorted(params_with_headers.keys()) values = list(map(params_with_headers.get, keys)) querystring = urlencode(list(zip(keys, values))).replace('+', '%20') amzdate = timenow.strftime('%Y%m%dT%H%M%SZ') datestamp = timenow.strftime('%Y%m%d') new_headers = {} if isinstance(headers, dict): new_headers = headers.copy() # Create payload hash (hash of the request body content). For GET # requests, the payload is an empty string (''). if not payload_hash: payload_hash = salt.utils.hashutils.sha256_digest(data) new_headers['X-Amz-date'] = amzdate new_headers['host'] = endpoint new_headers['x-amz-content-sha256'] = payload_hash a_canonical_headers = [] a_signed_headers = [] if token != '': new_headers['X-Amz-security-token'] = token for header in sorted(new_headers.keys(), key=six.text_type.lower): lower_header = header.lower() a_canonical_headers.append('{0}:{1}'.format(lower_header, new_headers[header].strip())) a_signed_headers.append(lower_header) canonical_headers = '\n'.join(a_canonical_headers) + '\n' signed_headers = ';'.join(a_signed_headers) algorithm = 'AWS4-HMAC-SHA256' # Combine elements to create create canonical request canonical_request = '\n'.join(( method, uri, querystring, canonical_headers, signed_headers, payload_hash )) # Create the string to sign credential_scope = '/'.join((datestamp, location, product, 'aws4_request')) string_to_sign = '\n'.join(( algorithm, amzdate, credential_scope, salt.utils.hashutils.sha256_digest(canonical_request) )) # Create the signing key using the function defined above. signing_key = _sig_key( secret_access_key, datestamp, location, product ) # Sign the string_to_sign using the signing_key signature = hmac.new( signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() # Add signing information to the request authorization_header = ( '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}' ).format( algorithm, access_key_id, credential_scope, signed_headers, signature, ) new_headers['Authorization'] = authorization_header requesturl = '{0}?{1}'.format(requesturl, querystring) return new_headers, requesturl
[ "def", "sig4", "(", "method", ",", "endpoint", ",", "params", ",", "prov_dict", ",", "aws_api_version", "=", "DEFAULT_AWS_API_VERSION", ",", "location", "=", "None", ",", "product", "=", "'ec2'", ",", "uri", "=", "'/'", ",", "requesturl", "=", "None", ",",...
Sign a query against AWS services using Signature Version 4 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
[ "Sign", "a", "query", "against", "AWS", "services", "using", "Signature", "Version", "4", "Signing", "Process", ".", "This", "is", "documented", "at", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L235-L343
train
saltstack/salt
salt/utils/aws.py
_sig_key
def _sig_key(key, date_stamp, regionName, serviceName): ''' Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp) if regionName: kRegion = _sign(kDate, regionName) kService = _sign(kRegion, serviceName) else: kService = _sign(kDate, serviceName) kSigning = _sign(kService, 'aws4_request') return kSigning
python
def _sig_key(key, date_stamp, regionName, serviceName): ''' Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python ''' kDate = _sign(('AWS4' + key).encode('utf-8'), date_stamp) if regionName: kRegion = _sign(kDate, regionName) kService = _sign(kRegion, serviceName) else: kService = _sign(kDate, serviceName) kSigning = _sign(kService, 'aws4_request') return kSigning
[ "def", "_sig_key", "(", "key", ",", "date_stamp", ",", "regionName", ",", "serviceName", ")", ":", "kDate", "=", "_sign", "(", "(", "'AWS4'", "+", "key", ")", ".", "encode", "(", "'utf-8'", ")", ",", "date_stamp", ")", "if", "regionName", ":", "kRegion...
Get a signature key. See: http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
[ "Get", "a", "signature", "key", ".", "See", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L355-L368
train
saltstack/salt
salt/utils/aws.py
query
def query(params=None, setname=None, requesturl=None, location=None, return_url=False, return_root=False, opts=None, provider=None, endpoint=None, product='ec2', sigver='2'): ''' Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service) ''' if params is None: params = {} if opts is None: opts = {} function = opts.get('function', (None, product)) providers = opts.get('providers', {}) if provider is None: prov_dict = providers.get(function[1], {}).get(product, {}) if prov_dict: driver = list(list(prov_dict.keys()))[0] provider = providers.get(driver, product) else: prov_dict = providers.get(provider, {}).get(product, {}) service_url = prov_dict.get('service_url', 'amazonaws.com') if not location: location = get_location(opts, prov_dict) if endpoint is None: if not requesturl: endpoint = prov_dict.get( 'endpoint', '{0}.{1}.{2}'.format(product, location, service_url) ) requesturl = 'https://{0}/'.format(endpoint) else: endpoint = urlparse(requesturl).netloc if endpoint == '': endpoint_err = ('Could not find a valid endpoint in the ' 'requesturl: {0}. Looking for something ' 'like https://some.aws.endpoint/?args').format( requesturl ) log.error(endpoint_err) if return_url is True: return {'error': endpoint_err}, requesturl return {'error': endpoint_err} log.debug('Using AWS endpoint: %s', endpoint) method = 'GET' aws_api_version = prov_dict.get( 'aws_api_version', prov_dict.get( '{0}_api_version'.format(product), DEFAULT_AWS_API_VERSION ) ) # Fallback to ec2's id & key if none is found, for this component if not prov_dict.get('id', None): prov_dict['id'] = providers.get(provider, {}).get('ec2', {}).get('id', {}) prov_dict['key'] = providers.get(provider, {}).get('ec2', {}).get('key', {}) if sigver == '4': headers, requesturl = sig4( method, endpoint, params, prov_dict, aws_api_version, location, product, requesturl=requesturl ) params_with_headers = {} else: params_with_headers = sig2( method, endpoint, params, prov_dict, aws_api_version ) headers = {} attempts = 0 while attempts < AWS_MAX_RETRIES: log.debug('AWS Request: %s', requesturl) log.trace('AWS Request Parameters: %s', params_with_headers) try: result = requests.get(requesturl, headers=headers, params=params_with_headers) log.debug('AWS Response Status Code: %s', result.status_code) log.trace( 'AWS Response Text: %s', result.text ) result.raise_for_status() break except requests.exceptions.HTTPError as exc: root = ET.fromstring(exc.response.content) data = xml.to_dict(root) # check to see if we should retry the query err_code = data.get('Errors', {}).get('Error', {}).get('Code', '') if attempts < AWS_MAX_RETRIES and err_code and err_code in AWS_RETRY_CODES: attempts += 1 log.error( 'AWS Response Status Code and Error: [%s %s] %s; ' 'Attempts remaining: %s', exc.response.status_code, exc, data, attempts ) sleep_exponential_backoff(attempts) continue log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} else: log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} root = ET.fromstring(result.text) items = root[1] if return_root is True: items = root if setname: if sys.version_info < (2, 7): children_len = len(root.getchildren()) else: children_len = len(root) for item in range(0, children_len): comps = root[item].tag.split('}') if comps[1] == setname: items = root[item] ret = [] for item in items: ret.append(xml.to_dict(item)) if return_url is True: return ret, requesturl return ret
python
def query(params=None, setname=None, requesturl=None, location=None, return_url=False, return_root=False, opts=None, provider=None, endpoint=None, product='ec2', sigver='2'): ''' Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service) ''' if params is None: params = {} if opts is None: opts = {} function = opts.get('function', (None, product)) providers = opts.get('providers', {}) if provider is None: prov_dict = providers.get(function[1], {}).get(product, {}) if prov_dict: driver = list(list(prov_dict.keys()))[0] provider = providers.get(driver, product) else: prov_dict = providers.get(provider, {}).get(product, {}) service_url = prov_dict.get('service_url', 'amazonaws.com') if not location: location = get_location(opts, prov_dict) if endpoint is None: if not requesturl: endpoint = prov_dict.get( 'endpoint', '{0}.{1}.{2}'.format(product, location, service_url) ) requesturl = 'https://{0}/'.format(endpoint) else: endpoint = urlparse(requesturl).netloc if endpoint == '': endpoint_err = ('Could not find a valid endpoint in the ' 'requesturl: {0}. Looking for something ' 'like https://some.aws.endpoint/?args').format( requesturl ) log.error(endpoint_err) if return_url is True: return {'error': endpoint_err}, requesturl return {'error': endpoint_err} log.debug('Using AWS endpoint: %s', endpoint) method = 'GET' aws_api_version = prov_dict.get( 'aws_api_version', prov_dict.get( '{0}_api_version'.format(product), DEFAULT_AWS_API_VERSION ) ) # Fallback to ec2's id & key if none is found, for this component if not prov_dict.get('id', None): prov_dict['id'] = providers.get(provider, {}).get('ec2', {}).get('id', {}) prov_dict['key'] = providers.get(provider, {}).get('ec2', {}).get('key', {}) if sigver == '4': headers, requesturl = sig4( method, endpoint, params, prov_dict, aws_api_version, location, product, requesturl=requesturl ) params_with_headers = {} else: params_with_headers = sig2( method, endpoint, params, prov_dict, aws_api_version ) headers = {} attempts = 0 while attempts < AWS_MAX_RETRIES: log.debug('AWS Request: %s', requesturl) log.trace('AWS Request Parameters: %s', params_with_headers) try: result = requests.get(requesturl, headers=headers, params=params_with_headers) log.debug('AWS Response Status Code: %s', result.status_code) log.trace( 'AWS Response Text: %s', result.text ) result.raise_for_status() break except requests.exceptions.HTTPError as exc: root = ET.fromstring(exc.response.content) data = xml.to_dict(root) # check to see if we should retry the query err_code = data.get('Errors', {}).get('Error', {}).get('Code', '') if attempts < AWS_MAX_RETRIES and err_code and err_code in AWS_RETRY_CODES: attempts += 1 log.error( 'AWS Response Status Code and Error: [%s %s] %s; ' 'Attempts remaining: %s', exc.response.status_code, exc, data, attempts ) sleep_exponential_backoff(attempts) continue log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} else: log.error( 'AWS Response Status Code and Error: [%s %s] %s', exc.response.status_code, exc, data ) if return_url is True: return {'error': data}, requesturl return {'error': data} root = ET.fromstring(result.text) items = root[1] if return_root is True: items = root if setname: if sys.version_info < (2, 7): children_len = len(root.getchildren()) else: children_len = len(root) for item in range(0, children_len): comps = root[item].tag.split('}') if comps[1] == setname: items = root[item] ret = [] for item in items: ret.append(xml.to_dict(item)) if return_url is True: return ret, requesturl return ret
[ "def", "query", "(", "params", "=", "None", ",", "setname", "=", "None", ",", "requesturl", "=", "None", ",", "location", "=", "None", ",", "return_url", "=", "False", ",", "return_root", "=", "False", ",", "opts", "=", "None", ",", "provider", "=", ...
Perform a query against AWS services using Signature Version 2 Signing Process. This is documented at: http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html Regions and endpoints are documented at: http://docs.aws.amazon.com/general/latest/gr/rande.html Default ``product`` is ``ec2``. Valid ``product`` names are: .. code-block: yaml - autoscaling (Auto Scaling) - cloudformation (CloudFormation) - ec2 (Elastic Compute Cloud) - elasticache (ElastiCache) - elasticbeanstalk (Elastic BeanStalk) - elasticloadbalancing (Elastic Load Balancing) - elasticmapreduce (Elastic MapReduce) - iam (Identity and Access Management) - importexport (Import/Export) - monitoring (CloudWatch) - rds (Relational Database Service) - simpledb (SimpleDB) - sns (Simple Notification Service) - sqs (Simple Queue Service)
[ "Perform", "a", "query", "against", "AWS", "services", "using", "Signature", "Version", "2", "Signing", "Process", ".", "This", "is", "documented", "at", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L371-L540
train
saltstack/salt
salt/utils/aws.py
get_region_from_metadata
def get_region_from_metadata(): ''' Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6 ''' global __Location__ if __Location__ == 'do-not-get-from-metadata': log.debug('Previously failed to get AWS region from metadata. Not trying again.') return None # Cached region if __Location__ != '': return __Location__ try: # Connections to instance meta-data must fail fast and never be proxied result = requests.get( "http://169.254.169.254/latest/dynamic/instance-identity/document", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) except requests.exceptions.RequestException: log.warning('Failed to get AWS region from instance metadata.', exc_info=True) # Do not try again __Location__ = 'do-not-get-from-metadata' return None try: region = result.json()['region'] __Location__ = region return __Location__ except (ValueError, KeyError): log.warning('Failed to decode JSON from instance metadata.') return None return None
python
def get_region_from_metadata(): ''' Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6 ''' global __Location__ if __Location__ == 'do-not-get-from-metadata': log.debug('Previously failed to get AWS region from metadata. Not trying again.') return None # Cached region if __Location__ != '': return __Location__ try: # Connections to instance meta-data must fail fast and never be proxied result = requests.get( "http://169.254.169.254/latest/dynamic/instance-identity/document", proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT, ) except requests.exceptions.RequestException: log.warning('Failed to get AWS region from instance metadata.', exc_info=True) # Do not try again __Location__ = 'do-not-get-from-metadata' return None try: region = result.json()['region'] __Location__ = region return __Location__ except (ValueError, KeyError): log.warning('Failed to decode JSON from instance metadata.') return None return None
[ "def", "get_region_from_metadata", "(", ")", ":", "global", "__Location__", "if", "__Location__", "==", "'do-not-get-from-metadata'", ":", "log", ".", "debug", "(", "'Previously failed to get AWS region from metadata. Not trying again.'", ")", "return", "None", "# Cached regi...
Try to get region from instance identity document and cache it .. versionadded:: 2015.5.6
[ "Try", "to", "get", "region", "from", "instance", "identity", "document", "and", "cache", "it" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L543-L579
train
saltstack/salt
salt/utils/aws.py
get_location
def get_location(opts=None, provider=None): ''' Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION ''' if opts is None: opts = {} ret = opts.get('location') if ret is None and provider is not None: ret = provider.get('location') if ret is None: ret = get_region_from_metadata() if ret is None: ret = DEFAULT_LOCATION return ret
python
def get_location(opts=None, provider=None): ''' Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION ''' if opts is None: opts = {} ret = opts.get('location') if ret is None and provider is not None: ret = provider.get('location') if ret is None: ret = get_region_from_metadata() if ret is None: ret = DEFAULT_LOCATION return ret
[ "def", "get_location", "(", "opts", "=", "None", ",", "provider", "=", "None", ")", ":", "if", "opts", "is", "None", ":", "opts", "=", "{", "}", "ret", "=", "opts", ".", "get", "(", "'location'", ")", "if", "ret", "is", "None", "and", "provider", ...
Return the region to use, in this order: opts['location'] provider['location'] get_region_from_metadata() DEFAULT_LOCATION
[ "Return", "the", "region", "to", "use", "in", "this", "order", ":", "opts", "[", "location", "]", "provider", "[", "location", "]", "get_region_from_metadata", "()", "DEFAULT_LOCATION" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/aws.py#L582-L599
train
saltstack/salt
salt/daemons/__init__.py
extract_masters
def extract_masters(opts, masters='master', port=None, raise_if_empty=True): ''' Parses opts and generates a list of master (host,port) addresses. By default looks for list of masters in opts['master'] and uses opts['master_port'] as the default port when otherwise not provided. Use the opts key given by masters for the masters list, default is 'master' If parameter port is not None then uses the default port given by port Returns a list of host address dicts of the form [ { 'external': (host,port), 'internal': (host, port) }, ... ] When only one address is provided it is assigned to the external address field When not provided the internal address field is set to None. For a given master the syntax options are as follows: hostname [port] external: hostname [port] [internal: hostaddress [port]] Where the hostname string could be either an FQDN or host address in dotted number notation. master.example.com 10.0.2.110 And the hostadress is in dotted number notation The space delimited port is optional and if not provided a default is used. The internal address is optional and if not provided is set to None Examples showing the YAML in /etc/salt/master conf file: 1) Single host name string (fqdn or dotted address) a) master: me.example.com b) master: localhost c) master: 10.0.2.205 2) Single host name string with port a) master: me.example.com 4506 b) master: 10.0.2.205 4510 3) Single master with external and optional internal host addresses for nat in a dict master: external: me.example.com 4506 internal: 10.0.2.100 4506 3) One or host host names with optional ports in a list master: - me.example.com 4506 - you.example.com 4510 - 8.8.8.8 - they.example.com 4506 - 8.8.4.4 4506 4) One or more host name with external and optional internal host addresses for Nat in a list of dicts master: - external: me.example.com 4506 internal: 10.0.2.100 4506 - external: you.example.com 4506 internal: 10.0.2.101 4506 - external: we.example.com - they.example.com ''' if port is not None: master_port = opts.get(port) else: master_port = opts.get('master_port') try: master_port = int(master_port) except ValueError: master_port = None if not master_port: emsg = "Invalid or missing opts['master_port']." log.error(emsg) raise ValueError(emsg) entries = opts.get(masters, []) if not entries: emsg = "Invalid or missing opts['{0}'].".format(masters) log.error(emsg) if raise_if_empty: raise ValueError(emsg) hostages = [] # extract candidate hostage (hostname dict) from entries if is_non_string_sequence(entries): # multiple master addresses provided for entry in entries: if isinstance(entry, Mapping): # mapping external = entry.get('external', '') internal = entry.get('internal', '') hostages.append(dict(external=external, internal=internal)) elif isinstance(entry, six.string_types): # string external = entry internal = '' hostages.append(dict(external=external, internal=internal)) elif isinstance(entries, Mapping): # mapping external = entries.get('external', '') internal = entries.get('internal', '') hostages.append(dict(external=external, internal=internal)) elif isinstance(entries, six.string_types): # string external = entries internal = '' hostages.append(dict(external=external, internal=internal)) # now parse each hostname string for host and optional port masters = [] for hostage in hostages: external = hostage['external'] internal = hostage['internal'] if external: external = parse_hostname(external, master_port) if not external: continue # must have a valid external host address internal = parse_hostname(internal, master_port) masters.append(dict(external=external, internal=internal)) return masters
python
def extract_masters(opts, masters='master', port=None, raise_if_empty=True): ''' Parses opts and generates a list of master (host,port) addresses. By default looks for list of masters in opts['master'] and uses opts['master_port'] as the default port when otherwise not provided. Use the opts key given by masters for the masters list, default is 'master' If parameter port is not None then uses the default port given by port Returns a list of host address dicts of the form [ { 'external': (host,port), 'internal': (host, port) }, ... ] When only one address is provided it is assigned to the external address field When not provided the internal address field is set to None. For a given master the syntax options are as follows: hostname [port] external: hostname [port] [internal: hostaddress [port]] Where the hostname string could be either an FQDN or host address in dotted number notation. master.example.com 10.0.2.110 And the hostadress is in dotted number notation The space delimited port is optional and if not provided a default is used. The internal address is optional and if not provided is set to None Examples showing the YAML in /etc/salt/master conf file: 1) Single host name string (fqdn or dotted address) a) master: me.example.com b) master: localhost c) master: 10.0.2.205 2) Single host name string with port a) master: me.example.com 4506 b) master: 10.0.2.205 4510 3) Single master with external and optional internal host addresses for nat in a dict master: external: me.example.com 4506 internal: 10.0.2.100 4506 3) One or host host names with optional ports in a list master: - me.example.com 4506 - you.example.com 4510 - 8.8.8.8 - they.example.com 4506 - 8.8.4.4 4506 4) One or more host name with external and optional internal host addresses for Nat in a list of dicts master: - external: me.example.com 4506 internal: 10.0.2.100 4506 - external: you.example.com 4506 internal: 10.0.2.101 4506 - external: we.example.com - they.example.com ''' if port is not None: master_port = opts.get(port) else: master_port = opts.get('master_port') try: master_port = int(master_port) except ValueError: master_port = None if not master_port: emsg = "Invalid or missing opts['master_port']." log.error(emsg) raise ValueError(emsg) entries = opts.get(masters, []) if not entries: emsg = "Invalid or missing opts['{0}'].".format(masters) log.error(emsg) if raise_if_empty: raise ValueError(emsg) hostages = [] # extract candidate hostage (hostname dict) from entries if is_non_string_sequence(entries): # multiple master addresses provided for entry in entries: if isinstance(entry, Mapping): # mapping external = entry.get('external', '') internal = entry.get('internal', '') hostages.append(dict(external=external, internal=internal)) elif isinstance(entry, six.string_types): # string external = entry internal = '' hostages.append(dict(external=external, internal=internal)) elif isinstance(entries, Mapping): # mapping external = entries.get('external', '') internal = entries.get('internal', '') hostages.append(dict(external=external, internal=internal)) elif isinstance(entries, six.string_types): # string external = entries internal = '' hostages.append(dict(external=external, internal=internal)) # now parse each hostname string for host and optional port masters = [] for hostage in hostages: external = hostage['external'] internal = hostage['internal'] if external: external = parse_hostname(external, master_port) if not external: continue # must have a valid external host address internal = parse_hostname(internal, master_port) masters.append(dict(external=external, internal=internal)) return masters
[ "def", "extract_masters", "(", "opts", ",", "masters", "=", "'master'", ",", "port", "=", "None", ",", "raise_if_empty", "=", "True", ")", ":", "if", "port", "is", "not", "None", ":", "master_port", "=", "opts", ".", "get", "(", "port", ")", "else", ...
Parses opts and generates a list of master (host,port) addresses. By default looks for list of masters in opts['master'] and uses opts['master_port'] as the default port when otherwise not provided. Use the opts key given by masters for the masters list, default is 'master' If parameter port is not None then uses the default port given by port Returns a list of host address dicts of the form [ { 'external': (host,port), 'internal': (host, port) }, ... ] When only one address is provided it is assigned to the external address field When not provided the internal address field is set to None. For a given master the syntax options are as follows: hostname [port] external: hostname [port] [internal: hostaddress [port]] Where the hostname string could be either an FQDN or host address in dotted number notation. master.example.com 10.0.2.110 And the hostadress is in dotted number notation The space delimited port is optional and if not provided a default is used. The internal address is optional and if not provided is set to None Examples showing the YAML in /etc/salt/master conf file: 1) Single host name string (fqdn or dotted address) a) master: me.example.com b) master: localhost c) master: 10.0.2.205 2) Single host name string with port a) master: me.example.com 4506 b) master: 10.0.2.205 4510 3) Single master with external and optional internal host addresses for nat in a dict master: external: me.example.com 4506 internal: 10.0.2.100 4506 3) One or host host names with optional ports in a list master: - me.example.com 4506 - you.example.com 4510 - 8.8.8.8 - they.example.com 4506 - 8.8.4.4 4506 4) One or more host name with external and optional internal host addresses for Nat in a list of dicts master: - external: me.example.com 4506 internal: 10.0.2.100 4506 - external: you.example.com 4506 internal: 10.0.2.101 4506 - external: we.example.com - they.example.com
[ "Parses", "opts", "and", "generates", "a", "list", "of", "master", "(", "host", "port", ")", "addresses", ".", "By", "default", "looks", "for", "list", "of", "masters", "in", "opts", "[", "master", "]", "and", "uses", "opts", "[", "master_port", "]", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/daemons/__init__.py#L48-L197
train
saltstack/salt
salt/daemons/__init__.py
parse_hostname
def parse_hostname(hostname, default_port): ''' Parse hostname string and return a tuple of (host, port) If port missing in hostname string then use default_port If anything is not a valid then return None hostname should contain a host and an option space delimited port host port As an attempt to prevent foolish mistakes the parser also tries to identify the port when it is colon delimited not space delimited. As in host:port. This is problematic since IPV6 addresses may have colons in them. Consequently the use of colon delimited ports is strongly discouraged. An ipv6 address must have at least 2 colons. ''' try: host, sep, port = hostname.strip().rpartition(' ') if not port: # invalid nothing there return None if not host: # no space separated port, only host as port use default port host = port port = default_port # ipv6 must have two or more colons if host.count(':') == 1: # only one so may be using colon delimited port host, sep, port = host.rpartition(':') if not host: # colon but not host so invalid return None if not port: # colon but no port so use default port = default_port host = host.strip() try: port = int(port) except ValueError: return None except AttributeError: return None return (host, port)
python
def parse_hostname(hostname, default_port): ''' Parse hostname string and return a tuple of (host, port) If port missing in hostname string then use default_port If anything is not a valid then return None hostname should contain a host and an option space delimited port host port As an attempt to prevent foolish mistakes the parser also tries to identify the port when it is colon delimited not space delimited. As in host:port. This is problematic since IPV6 addresses may have colons in them. Consequently the use of colon delimited ports is strongly discouraged. An ipv6 address must have at least 2 colons. ''' try: host, sep, port = hostname.strip().rpartition(' ') if not port: # invalid nothing there return None if not host: # no space separated port, only host as port use default port host = port port = default_port # ipv6 must have two or more colons if host.count(':') == 1: # only one so may be using colon delimited port host, sep, port = host.rpartition(':') if not host: # colon but not host so invalid return None if not port: # colon but no port so use default port = default_port host = host.strip() try: port = int(port) except ValueError: return None except AttributeError: return None return (host, port)
[ "def", "parse_hostname", "(", "hostname", ",", "default_port", ")", ":", "try", ":", "host", ",", "sep", ",", "port", "=", "hostname", ".", "strip", "(", ")", ".", "rpartition", "(", "' '", ")", "if", "not", "port", ":", "# invalid nothing there", "retur...
Parse hostname string and return a tuple of (host, port) If port missing in hostname string then use default_port If anything is not a valid then return None hostname should contain a host and an option space delimited port host port As an attempt to prevent foolish mistakes the parser also tries to identify the port when it is colon delimited not space delimited. As in host:port. This is problematic since IPV6 addresses may have colons in them. Consequently the use of colon delimited ports is strongly discouraged. An ipv6 address must have at least 2 colons.
[ "Parse", "hostname", "string", "and", "return", "a", "tuple", "of", "(", "host", "port", ")", "If", "port", "missing", "in", "hostname", "string", "then", "use", "default_port", "If", "anything", "is", "not", "a", "valid", "then", "return", "None" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/daemons/__init__.py#L200-L240
train
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_objects
def find_objects(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects(regex) return lines
python
def find_objects(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects(regex) return lines
[ "def", "find_objects", "(", "config", "=", "None", ",", "config_path", "=", "None", ",", "regex", "=", "None", ",", "saltenv", "=", "'base'", ")", ":", "ccp", "=", "_get_ccp", "(", "config", "=", "config", ",", "config_path", "=", "config_path", ",", "...
Return all the line objects that match the expression in the ``regex`` argument. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines <salt.ciscoconfparse_mod.find_lines>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects'](config_path='salt://path/to/config.txt', regex='Gigabit') for obj in objects: print(obj.text)
[ "Return", "all", "the", "line", "objects", "that", "match", "the", "expression", "in", "the", "regex", "argument", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L71-L111
train
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_lines
def find_lines(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address ''' lines = find_objects(config=config, config_path=config_path, regex=regex, saltenv=saltenv) return [line.text for line in lines]
python
def find_lines(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address ''' lines = find_objects(config=config, config_path=config_path, regex=regex, saltenv=saltenv) return [line.text for line in lines]
[ "def", "find_lines", "(", "config", "=", "None", ",", "config_path", "=", "None", ",", "regex", "=", "None", ",", "saltenv", "=", "'base'", ")", ":", "lines", "=", "find_objects", "(", "config", "=", "config", ",", "config_path", "=", "config_path", ",",...
Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. regex The regular expression to match the lines against. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines config_path=https://bit.ly/2mAdq7z regex='ip address' Output example: .. code-block:: text cisco-ios-router: - ip address dhcp - ip address 172.20.0.1 255.255.255.0 - no ip address
[ "Return", "all", "the", "lines", "(", "as", "text", ")", "that", "match", "the", "expression", "in", "the", "regex", "argument", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L114-L156
train
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_lines_w_child
def find_lines_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' ''' lines = find_objects_w_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines]
python
def find_lines_w_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' ''' lines = find_objects_w_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines]
[ "def", "find_lines_w_child", "(", "config", "=", "None", ",", "config_path", "=", "None", ",", "parent_regex", "=", "None", ",", "child_regex", "=", "None", ",", "ignore_ws", "=", "False", ",", "saltenv", "=", "'base'", ")", ":", "lines", "=", "find_object...
r''' Return a list of parent lines (as text) matching the regular expression ``parent_regex`` that have children lines matching ``child_regex``. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+'
[ "r", "Return", "a", "list", "of", "parent", "lines", "(", "as", "text", ")", "matching", "the", "regular", "expression", "parent_regex", "that", "have", "children", "lines", "matching", "child_regex", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L214-L261
train
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_objects_wo_child
def find_objects_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines
python
def find_objects_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text) ''' ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines
[ "def", "find_objects_wo_child", "(", "config", "=", "None", ",", "config_path", "=", "None", ",", "parent_regex", "=", "None", ",", "child_regex", "=", "None", ",", "ignore_ws", "=", "False", ",", "saltenv", "=", "'base'", ")", ":", "ccp", "=", "_get_ccp",...
Return a list of parent ``ciscoconfparse.IOSCfgLine`` objects, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` objects will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. .. warning:: This function is mostly valuable when invoked from other Salt components (i.e., execution modules, states, templates etc.). For CLI usage, please consider using :py:func:`ciscoconfparse.find_lines_wo_child <salt.ciscoconfparse_mod.find_lines_wo_child>` config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. Usage example: .. code-block:: python objects = __salt__['ciscoconfparse.find_objects_wo_child'](config_path='https://bit.ly/2mAdq7z', parent_regex='line con', child_regex='stopbits') for obj in objects: print(obj.text)
[ "Return", "a", "list", "of", "parent", "ciscoconfparse", ".", "IOSCfgLine", "objects", "which", "matched", "the", "parent_regex", "and", "whose", "children", "did", "*", "not", "*", "match", "child_regex", ".", "Only", "the", "parent", "ciscoconfparse", ".", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L264-L319
train
saltstack/salt
salt/modules/ciscoconfparse_mod.py
find_lines_wo_child
def find_lines_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' ''' lines = find_objects_wo_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines]
python
def find_lines_wo_child(config=None, config_path=None, parent_regex=None, child_regex=None, ignore_ws=False, saltenv='base'): ''' Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' ''' lines = find_objects_wo_child(config=config, config_path=config_path, parent_regex=parent_regex, child_regex=child_regex, ignore_ws=ignore_ws, saltenv=saltenv) return [line.text for line in lines]
[ "def", "find_lines_wo_child", "(", "config", "=", "None", ",", "config_path", "=", "None", ",", "parent_regex", "=", "None", ",", "child_regex", "=", "None", ",", "ignore_ws", "=", "False", ",", "saltenv", "=", "'base'", ")", ":", "lines", "=", "find_objec...
Return a list of parent ``ciscoconfparse.IOSCfgLine`` lines as text, which matched the ``parent_regex`` and whose children did *not* match ``child_regex``. Only the parent ``ciscoconfparse.IOSCfgLine`` text lines will be returned. For simplicity, this method only finds oldest ancestors without immediate children that match. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. config_path The absolute or remote path to the file with the configuration to be parsed. This argument supports the usual Salt filesystem URIs, e.g., ``salt://``, ``https://``, ``ftp://``, ``s3://``, etc. parent_regex The regular expression to match the parent lines against. child_regex The regular expression to match the child lines against. ignore_ws: ``False`` Whether to ignore the white spaces. saltenv: ``base`` Salt fileserver environment from which to retrieve the file. This argument is ignored when ``config_path`` is not a ``salt://`` URL. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.find_lines_wo_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits'
[ "Return", "a", "list", "of", "parent", "ciscoconfparse", ".", "IOSCfgLine", "lines", "as", "text", "which", "matched", "the", "parent_regex", "and", "whose", "children", "did", "*", "not", "*", "match", "child_regex", ".", "Only", "the", "parent", "ciscoconfpa...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L322-L371
train
saltstack/salt
salt/modules/ciscoconfparse_mod.py
filter_lines
def filter_lines(config=None, config_path=None, parent_regex=None, child_regex=None, saltenv='base'): ''' Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ] ''' ret = [] ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) parent_lines = ccp.find_objects(parent_regex) for parent_line in parent_lines: child_lines = parent_line.re_search_children(child_regex) if child_lines: for child_line in child_lines: ret.append({ 'match': True, 'parent': parent_line.text, 'child': child_line.text }) else: ret.append({ 'match': False, 'parent': parent_line.text, 'child': None }) return ret
python
def filter_lines(config=None, config_path=None, parent_regex=None, child_regex=None, saltenv='base'): ''' Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ] ''' ret = [] ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) parent_lines = ccp.find_objects(parent_regex) for parent_line in parent_lines: child_lines = parent_line.re_search_children(child_regex) if child_lines: for child_line in child_lines: ret.append({ 'match': True, 'parent': parent_line.text, 'child': child_line.text }) else: ret.append({ 'match': False, 'parent': parent_line.text, 'child': None }) return ret
[ "def", "filter_lines", "(", "config", "=", "None", ",", "config_path", "=", "None", ",", "parent_regex", "=", "None", ",", "child_regex", "=", "None", ",", "saltenv", "=", "'base'", ")", ":", "ret", "=", "[", "]", "ccp", "=", "_get_ccp", "(", "config",...
Return a list of detailed matches, for the configuration blocks (parent-child relationship) whose parent respects the regular expressions configured via the ``parent_regex`` argument, and the child matches the ``child_regex`` regular expression. The result is a list of dictionaries with the following keys: - ``match``: a boolean value that tells whether ``child_regex`` matched any children lines. - ``parent``: the parent line (as text). - ``child``: the child line (as text). If no child line matched, this field will be ``None``. Note that the return list contains the elements that matched the parent condition, the ``parent_regex`` regular expression. Therefore, the ``parent`` field will always have a valid value, while ``match`` and ``child`` may default to ``False`` and ``None`` respectively when there is not child match. CLI Example: .. code-block:: bash salt '*' ciscoconfparse.filter_lines config_path=https://bit.ly/2mAdq7z parent_regex='Gigabit' child_regex='shutdown' Example output (for the example above): .. code-block:: python [ { 'parent': 'interface GigabitEthernet1', 'match': False, 'child': None }, { 'parent': 'interface GigabitEthernet2', 'match': True, 'child': ' shutdown' }, { 'parent': 'interface GigabitEthernet3', 'match': True, 'child': ' shutdown' } ]
[ "Return", "a", "list", "of", "detailed", "matches", "for", "the", "configuration", "blocks", "(", "parent", "-", "child", "relationship", ")", "whose", "parent", "respects", "the", "regular", "expressions", "configured", "via", "the", "parent_regex", "argument", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ciscoconfparse_mod.py#L374-L443
train
saltstack/salt
salt/states/tuned.py
profile
def profile(name): ''' This state module allows you to modify system tuned parameters Example tuned.sls file to set profile to virtual-guest tuned: tuned: - profile - name: virtual-guest name tuned profile name to set the system to To see a valid list of states call execution module: :py:func:`tuned.list <salt.modules.tuned.list_>` ''' # create data-structure to return with default value ret = {'name': '', 'changes': {}, 'result': False, 'comment': ''} ret[name] = name profile = name # get the current state of tuned-adm current_state = __salt__['tuned.active']() valid_profiles = __salt__['tuned.list']() # check valid profiles, and return error if profile name is not valid if profile not in valid_profiles: raise salt.exceptions.SaltInvocationError('Invalid Profile Name') # if current state is same as requested state, return without doing much if profile in current_state: ret['result'] = True ret['comment'] = 'System already in the correct state' return ret # test mode if __opts__['test'] is True: ret['comment'] = 'The state of "{0}" will be changed.'.format( current_state) ret['changes'] = { 'old': current_state, 'new': 'Profile will be set to {0}'.format(profile), } # return None when testing ret['result'] = None return ret # we come to this stage if current state is different that requested state # we there have to set the new state request new_state = __salt__['tuned.profile'](profile) # create the comment data structure ret['comment'] = 'The state of "{0}" was changed!'.format(profile) # fill in the ret data structure ret['changes'] = { 'old': current_state, 'new': new_state, } ret['result'] = True # return with the dictionary data structure return ret
python
def profile(name): ''' This state module allows you to modify system tuned parameters Example tuned.sls file to set profile to virtual-guest tuned: tuned: - profile - name: virtual-guest name tuned profile name to set the system to To see a valid list of states call execution module: :py:func:`tuned.list <salt.modules.tuned.list_>` ''' # create data-structure to return with default value ret = {'name': '', 'changes': {}, 'result': False, 'comment': ''} ret[name] = name profile = name # get the current state of tuned-adm current_state = __salt__['tuned.active']() valid_profiles = __salt__['tuned.list']() # check valid profiles, and return error if profile name is not valid if profile not in valid_profiles: raise salt.exceptions.SaltInvocationError('Invalid Profile Name') # if current state is same as requested state, return without doing much if profile in current_state: ret['result'] = True ret['comment'] = 'System already in the correct state' return ret # test mode if __opts__['test'] is True: ret['comment'] = 'The state of "{0}" will be changed.'.format( current_state) ret['changes'] = { 'old': current_state, 'new': 'Profile will be set to {0}'.format(profile), } # return None when testing ret['result'] = None return ret # we come to this stage if current state is different that requested state # we there have to set the new state request new_state = __salt__['tuned.profile'](profile) # create the comment data structure ret['comment'] = 'The state of "{0}" was changed!'.format(profile) # fill in the ret data structure ret['changes'] = { 'old': current_state, 'new': new_state, } ret['result'] = True # return with the dictionary data structure return ret
[ "def", "profile", "(", "name", ")", ":", "# create data-structure to return with default value", "ret", "=", "{", "'name'", ":", "''", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "ret", "[", "name", "]"...
This state module allows you to modify system tuned parameters Example tuned.sls file to set profile to virtual-guest tuned: tuned: - profile - name: virtual-guest name tuned profile name to set the system to To see a valid list of states call execution module: :py:func:`tuned.list <salt.modules.tuned.list_>`
[ "This", "state", "module", "allows", "you", "to", "modify", "system", "tuned", "parameters" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/tuned.py#L18-L86
train
saltstack/salt
salt/modules/napalm_probes.py
delete_probes
def delete_probes(probes, test=False, commit=True, **kwargs): # pylint: disable=unused-argument ''' Removes RPM/SLA probes from the network device. Calls the configuration template 'delete_probes' from the NAPALM library, providing as input a rich formatted dictionary with the configuration details of the probes to be removed from the configuration of the device. :param probes: Dictionary with a similar format as the output dictionary of the function config(), where the details are not necessary. :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: A dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied Input example: .. code-block:: python probes = { 'existing_probe':{ 'existing_test1': {}, 'existing_test2': {} } } ''' return __salt__['net.load_template']('delete_probes', probes=probes, test=test, commit=commit, inherit_napalm_device=napalm_device)
python
def delete_probes(probes, test=False, commit=True, **kwargs): # pylint: disable=unused-argument ''' Removes RPM/SLA probes from the network device. Calls the configuration template 'delete_probes' from the NAPALM library, providing as input a rich formatted dictionary with the configuration details of the probes to be removed from the configuration of the device. :param probes: Dictionary with a similar format as the output dictionary of the function config(), where the details are not necessary. :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: A dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied Input example: .. code-block:: python probes = { 'existing_probe':{ 'existing_test1': {}, 'existing_test2': {} } } ''' return __salt__['net.load_template']('delete_probes', probes=probes, test=test, commit=commit, inherit_napalm_device=napalm_device)
[ "def", "delete_probes", "(", "probes", ",", "test", "=", "False", ",", "commit", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "return", "__salt__", "[", "'net.load_template'", "]", "(", "'delete_probes'", ",", "probes", ...
Removes RPM/SLA probes from the network device. Calls the configuration template 'delete_probes' from the NAPALM library, providing as input a rich formatted dictionary with the configuration details of the probes to be removed from the configuration of the device. :param probes: Dictionary with a similar format as the output dictionary of the function config(), where the details are not necessary. :param test: Dry run? If set as True, will apply the config, discard and return the changes. Default: False :param commit: Commit? (default: True) Sometimes it is not needed to commit the config immediately after loading the changes. E.g.: a state loads a couple of parts (add / remove / update) and would not be optimal to commit after each operation. Also, from the CLI when the user needs to apply the similar changes before committing, can specify commit=False and will not discard the config. :raise MergeConfigException: If there is an error on the configuration sent. :return: A dictionary having the following keys: - result (bool): if the config was applied successfully. It is `False` only in case of failure. In case there are no changes to be applied and successfully performs all operations it is still `True` and so will be the `already_configured` flag (example below) - comment (str): a message for the user - already_configured (bool): flag to check if there were no changes applied - diff (str): returns the config changes applied Input example: .. code-block:: python probes = { 'existing_probe':{ 'existing_test1': {}, 'existing_test2': {} } }
[ "Removes", "RPM", "/", "SLA", "probes", "from", "the", "network", "device", ".", "Calls", "the", "configuration", "template", "delete_probes", "from", "the", "NAPALM", "library", "providing", "as", "input", "a", "rich", "formatted", "dictionary", "with", "the", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_probes.py#L273-L320
train
saltstack/salt
salt/returners/couchbase_return.py
_get_connection
def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN
python
def _get_connection(): ''' Global function to access the couchbase connection (and make it if its closed) ''' global COUCHBASE_CONN if COUCHBASE_CONN is None: opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket']) return COUCHBASE_CONN
[ "def", "_get_connection", "(", ")", ":", "global", "COUCHBASE_CONN", "if", "COUCHBASE_CONN", "is", "None", ":", "opts", "=", "_get_options", "(", ")", "if", "opts", "[", "'password'", "]", ":", "COUCHBASE_CONN", "=", "couchbase", ".", "Couchbase", ".", "conn...
Global function to access the couchbase connection (and make it if its closed)
[ "Global", "function", "to", "access", "the", "couchbase", "connection", "(", "and", "make", "it", "if", "its", "closed", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L106-L123
train
saltstack/salt
salt/returners/couchbase_return.py
_verify_views
def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True
python
def _verify_views(): ''' Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config ''' global VERIFIED_VIEWS if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False): return cb_ = _get_connection() ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"}, 'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"} } } try: curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value if curr_ddoc['views'] == ddoc['views']: VERIFIED_VIEWS = True return except couchbase.exceptions.HTTPError: pass cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False) VERIFIED_VIEWS = True
[ "def", "_verify_views", "(", ")", ":", "global", "VERIFIED_VIEWS", "if", "VERIFIED_VIEWS", "or", "__opts__", ".", "get", "(", "'couchbase.skip_verify_views'", ",", "False", ")", ":", "return", "cb_", "=", "_get_connection", "(", ")", "ddoc", "=", "{", "'views'...
Verify that you have the views you need. This can be disabled by adding couchbase.skip_verify_views: True in config
[ "Verify", "that", "you", "have", "the", "views", "you", "need", ".", "This", "can", "be", "disabled", "by", "adding", "couchbase", ".", "skip_verify_views", ":", "True", "in", "config" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L126-L150
train
saltstack/salt
salt/returners/couchbase_return.py
prep_jid
def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid
python
def prep_jid(nocache=False, passed_jid=None): ''' Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case ''' if passed_jid is None: jid = salt.utils.jid.gen_jid(__opts__) else: jid = passed_jid cb_ = _get_connection() try: cb_.add(six.text_type(jid), {'nocache': nocache}, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice if passed_jid is None: return prep_jid(nocache=nocache) return jid
[ "def", "prep_jid", "(", "nocache", "=", "False", ",", "passed_jid", "=", "None", ")", ":", "if", "passed_jid", "is", "None", ":", "jid", "=", "salt", ".", "utils", ".", "jid", ".", "gen_jid", "(", "__opts__", ")", "else", ":", "jid", "=", "passed_jid...
Return a job id and prepare the job id directory This is the function responsible for making sure jids don't collide (unless its passed a jid) So do what you have to do to make sure that stays the case
[ "Return", "a", "job", "id", "and", "prepare", "the", "job", "id", "directory", "This", "is", "the", "function", "responsible", "for", "making", "sure", "jids", "don", "t", "collide", "(", "unless", "its", "passed", "a", "jid", ")", "So", "do", "what", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L161-L185
train
saltstack/salt
salt/returners/couchbase_return.py
returner
def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False
python
def returner(load): ''' Return data to couchbase bucket ''' cb_ = _get_connection() hn_key = '{0}/{1}'.format(load['jid'], load['id']) try: ret_doc = {'return': load['return'], 'full_ret': salt.utils.json.dumps(load)} cb_.add(hn_key, ret_doc, ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( 'An extra return was detected from minion %s, please verify ' 'the minion, this could be a replay attack', load['id'] ) return False
[ "def", "returner", "(", "load", ")", ":", "cb_", "=", "_get_connection", "(", ")", "hn_key", "=", "'{0}/{1}'", ".", "format", "(", "load", "[", "'jid'", "]", ",", "load", "[", "'id'", "]", ")", "try", ":", "ret_doc", "=", "{", "'return'", ":", "loa...
Return data to couchbase bucket
[ "Return", "data", "to", "couchbase", "bucket" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L188-L208
train
saltstack/salt
salt/returners/couchbase_return.py
save_load
def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions)
python
def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.text_type(jid)) jid_doc.value['load'] = clear_load cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl()) # if you have a tgt, save that for the UI etc if 'tgt' in clear_load and clear_load['tgt'] != '': ckminions = salt.utils.minions.CkMinions(__opts__) # Retrieve the minions list _res = ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) minions = _res['minions'] save_minions(jid, minions)
[ "def", "save_load", "(", "jid", ",", "clear_load", ",", "minion", "=", "None", ")", ":", "cb_", "=", "_get_connection", "(", ")", "try", ":", "jid_doc", "=", "cb_", ".", "get", "(", "six", ".", "text_type", "(", "jid", ")", ")", "except", "couchbase"...
Save the load to the specified jid
[ "Save", "the", "load", "to", "the", "specified", "jid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L211-L235
train
saltstack/salt
salt/returners/couchbase_return.py
save_minions
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl())
python
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument ''' Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only. ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: log.warning('Could not write job cache file for jid: %s', jid) return False # save the minions to a cache so we can see in the UI if 'minions' in jid_doc.value: jid_doc.value['minions'] = sorted( set(jid_doc.value['minions'] + minions) ) else: jid_doc.value['minions'] = minions cb_.replace(six.text_type(jid), jid_doc.value, cas=jid_doc.cas, ttl=_get_ttl())
[ "def", "save_minions", "(", "jid", ",", "minions", ",", "syndic_id", "=", "None", ")", ":", "# pylint: disable=unused-argument", "cb_", "=", "_get_connection", "(", ")", "try", ":", "jid_doc", "=", "cb_", ".", "get", "(", "six", ".", "text_type", "(", "jid...
Save/update the minion list for a given jid. The syndic_id argument is included for API compatibility only.
[ "Save", "/", "update", "the", "minion", "list", "for", "a", "given", "jid", ".", "The", "syndic_id", "argument", "is", "included", "for", "API", "compatibility", "only", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L238-L258
train
saltstack/salt
salt/returners/couchbase_return.py
get_load
def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret
python
def get_load(jid): ''' Return the load data that marks a specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value['load'] ret['Minions'] = jid_doc.value['minions'] except KeyError as e: log.error(e) return ret
[ "def", "get_load", "(", "jid", ")", ":", "cb_", "=", "_get_connection", "(", ")", "try", ":", "jid_doc", "=", "cb_", ".", "get", "(", "six", ".", "text_type", "(", "jid", ")", ")", "except", "couchbase", ".", "exceptions", ".", "NotFoundError", ":", ...
Return the load data that marks a specified jid
[ "Return", "the", "load", "data", "that", "marks", "a", "specified", "jid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L261-L279
train
saltstack/salt
salt/returners/couchbase_return.py
get_jid
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret
python
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jid_returns', key=six.text_type(jid), include_docs=True): ret[result.value] = result.doc.value return ret
[ "def", "get_jid", "(", "jid", ")", ":", "cb_", "=", "_get_connection", "(", ")", "_verify_views", "(", ")", "ret", "=", "{", "}", "for", "result", "in", "cb_", ".", "query", "(", "DESIGN_NAME", ",", "'jid_returns'", ",", "key", "=", "six", ".", "text...
Return the information returned when the specified job id was executed
[ "Return", "the", "information", "returned", "when", "the", "specified", "job", "id", "was", "executed" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L282-L294
train
saltstack/salt
salt/returners/couchbase_return.py
get_jids
def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret
python
def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret
[ "def", "get_jids", "(", ")", ":", "cb_", "=", "_get_connection", "(", ")", "_verify_views", "(", ")", "ret", "=", "{", "}", "for", "result", "in", "cb_", ".", "query", "(", "DESIGN_NAME", ",", "'jids'", ",", "include_docs", "=", "True", ")", ":", "re...
Return a list of all job ids
[ "Return", "a", "list", "of", "all", "job", "ids" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L297-L309
train
saltstack/salt
salt/returners/couchbase_return.py
_format_jid_instance
def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
python
def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
[ "def", "_format_jid_instance", "(", "jid", ",", "job", ")", ":", "ret", "=", "_format_job_instance", "(", "job", ")", "ret", ".", "update", "(", "{", "'StartTime'", ":", "salt", ".", "utils", ".", "jid", ".", "jid_to_time", "(", "jid", ")", "}", ")", ...
Return a properly formatted jid dict
[ "Return", "a", "properly", "formatted", "jid", "dict" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L332-L338
train
saltstack/salt
salt/cache/redis_cache.py
_get_redis_cache_opts
def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), }
python
def _get_redis_cache_opts(): ''' Return the Redis server connection details from the __opts__. ''' return { 'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('cache.redis.db', '0'), 'password': __opts__.get('cache.redis.password', ''), 'cluster_mode': __opts__.get('cache.redis.cluster_mode', False), 'startup_nodes': __opts__.get('cache.redis.cluster.startup_nodes', {}), 'skip_full_coverage_check': __opts__.get('cache.redis.cluster.skip_full_coverage_check', False), }
[ "def", "_get_redis_cache_opts", "(", ")", ":", "return", "{", "'host'", ":", "__opts__", ".", "get", "(", "'cache.redis.host'", ",", "'localhost'", ")", ",", "'port'", ":", "__opts__", ".", "get", "(", "'cache.redis.port'", ",", "6379", ")", ",", "'unix_sock...
Return the Redis server connection details from the __opts__.
[ "Return", "the", "Redis", "server", "connection", "details", "from", "the", "__opts__", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L205-L218
train
saltstack/salt
salt/cache/redis_cache.py
_get_redis_server
def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER
python
def _get_redis_server(opts=None): ''' Return the Redis server instance. Caching the object instance. ''' global REDIS_SERVER if REDIS_SERVER: return REDIS_SERVER if not opts: opts = _get_redis_cache_opts() if opts['cluster_mode']: REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'], skip_full_coverage_check=opts['skip_full_coverage_check']) else: REDIS_SERVER = redis.StrictRedis(opts['host'], opts['port'], unix_socket_path=opts['unix_socket_path'], db=opts['db'], password=opts['password']) return REDIS_SERVER
[ "def", "_get_redis_server", "(", "opts", "=", "None", ")", ":", "global", "REDIS_SERVER", "if", "REDIS_SERVER", ":", "return", "REDIS_SERVER", "if", "not", "opts", ":", "opts", "=", "_get_redis_cache_opts", "(", ")", "if", "opts", "[", "'cluster_mode'", "]", ...
Return the Redis server instance. Caching the object instance.
[ "Return", "the", "Redis", "server", "instance", ".", "Caching", "the", "object", "instance", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L221-L241
train
saltstack/salt
salt/cache/redis_cache.py
_get_redis_keys_opts
def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) }
python
def _get_redis_keys_opts(): ''' Build the key opts based on the user options. ''' return { 'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX), 'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX), 'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX), 'separator': __opts__.get('cache.redis.separator', _SEPARATOR) }
[ "def", "_get_redis_keys_opts", "(", ")", ":", "return", "{", "'bank_prefix'", ":", "__opts__", ".", "get", "(", "'cache.redis.bank_prefix'", ",", "_BANK_PREFIX", ")", ",", "'bank_keys_prefix'", ":", "__opts__", ".", "get", "(", "'cache.redis.bank_keys_prefix'", ",",...
Build the key opts based on the user options.
[ "Build", "the", "key", "opts", "based", "on", "the", "user", "options", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L244-L253
train
saltstack/salt
salt/cache/redis_cache.py
_get_bank_redis_key
def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank )
python
def _get_bank_redis_key(bank): ''' Return the Redis key for the bank given the name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank )
[ "def", "_get_bank_redis_key", "(", "bank", ")", ":", "opts", "=", "_get_redis_keys_opts", "(", ")", "return", "'{prefix}{separator}{bank}'", ".", "format", "(", "prefix", "=", "opts", "[", "'bank_prefix'", "]", ",", "separator", "=", "opts", "[", "'separator'", ...
Return the Redis key for the bank given the name.
[ "Return", "the", "Redis", "key", "for", "the", "bank", "given", "the", "name", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L256-L265
train
saltstack/salt
salt/cache/redis_cache.py
_get_key_redis_key
def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key )
python
def _get_key_redis_key(bank, key): ''' Return the Redis key given the bank name and the key name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}/{key}'.format( prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key )
[ "def", "_get_key_redis_key", "(", "bank", ",", "key", ")", ":", "opts", "=", "_get_redis_keys_opts", "(", ")", "return", "'{prefix}{separator}{bank}/{key}'", ".", "format", "(", "prefix", "=", "opts", "[", "'key_prefix'", "]", ",", "separator", "=", "opts", "[...
Return the Redis key given the bank name and the key name.
[ "Return", "the", "Redis", "key", "given", "the", "bank", "name", "and", "the", "key", "name", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L268-L278
train
saltstack/salt
salt/cache/redis_cache.py
_get_bank_keys_redis_key
def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank )
python
def _get_bank_keys_redis_key(bank): ''' Return the Redis key for the SET of keys under a certain bank, given the bank name. ''' opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_keys_prefix'], separator=opts['separator'], bank=bank )
[ "def", "_get_bank_keys_redis_key", "(", "bank", ")", ":", "opts", "=", "_get_redis_keys_opts", "(", ")", "return", "'{prefix}{separator}{bank}'", ".", "format", "(", "prefix", "=", "opts", "[", "'bank_keys_prefix'", "]", ",", "separator", "=", "opts", "[", "'sep...
Return the Redis key for the SET of keys under a certain bank, given the bank name.
[ "Return", "the", "Redis", "key", "for", "the", "SET", "of", "keys", "under", "a", "certain", "bank", "given", "the", "bank", "name", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L281-L290
train
saltstack/salt
salt/cache/redis_cache.py
_build_bank_hier
def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True
python
def _build_bank_hier(bank, redis_pipe): ''' Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server. ''' bank_list = bank.split('/') parent_bank_path = bank_list[0] for bank_name in bank_list[1:]: prev_bank_redis_key = _get_bank_redis_key(parent_bank_path) redis_pipe.sadd(prev_bank_redis_key, bank_name) log.debug('Adding %s to %s', bank_name, prev_bank_redis_key) parent_bank_path = '{curr_path}/{bank_name}'.format( curr_path=parent_bank_path, bank_name=bank_name ) # this becomes the parent of the next return True
[ "def", "_build_bank_hier", "(", "bank", ",", "redis_pipe", ")", ":", "bank_list", "=", "bank", ".", "split", "(", "'/'", ")", "parent_bank_path", "=", "bank_list", "[", "0", "]", "for", "bank_name", "in", "bank_list", "[", "1", ":", "]", ":", "prev_bank_...
Build the bank hierarchy from the root of the tree. If already exists, it won't rewrite. It's using the Redis pipeline, so there will be only one interaction with the remote server.
[ "Build", "the", "bank", "hierarchy", "from", "the", "root", "of", "the", "tree", ".", "If", "already", "exists", "it", "won", "t", "rewrite", ".", "It", "s", "using", "the", "Redis", "pipeline", "so", "there", "will", "be", "only", "one", "interaction", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L293-L310
train
saltstack/salt
salt/cache/redis_cache.py
_get_banks_to_remove
def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove
python
def _get_banks_to_remove(redis_server, bank, path=''): ''' A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. ''' current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank) bank_paths_to_remove = [current_path] # as you got here, you'll be removed bank_key = _get_bank_redis_key(current_path) child_banks = redis_server.smembers(bank_key) if not child_banks: return bank_paths_to_remove # this bank does not have any child banks so we stop here for child_bank in child_banks: bank_paths_to_remove.extend(_get_banks_to_remove(redis_server, child_bank, path=current_path)) # go one more level deeper # and also remove the children of this child bank (if any) return bank_paths_to_remove
[ "def", "_get_banks_to_remove", "(", "redis_server", ",", "bank", ",", "path", "=", "''", ")", ":", "current_path", "=", "bank", "if", "not", "path", "else", "'{path}/{bank}'", ".", "format", "(", "path", "=", "path", ",", "bank", "=", "bank", ")", "bank_...
A simple tree tarversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree.
[ "A", "simple", "tree", "tarversal", "algorithm", "that", "builds", "the", "list", "of", "banks", "to", "remove", "starting", "from", "an", "arbitrary", "node", "in", "the", "tree", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L313-L330
train
saltstack/salt
salt/cache/redis_cache.py
store
def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
python
def store(bank, key, data): ''' Store the data in a Redis key. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() redis_key = _get_key_redis_key(bank, key) redis_bank_keys = _get_bank_keys_redis_key(bank) try: _build_bank_hier(bank, redis_pipe) value = __context__['serial'].dumps(data) redis_pipe.set(redis_key, value) log.debug('Setting the value for %s under %s (%s)', key, bank, redis_key) redis_pipe.sadd(redis_bank_keys, key) log.debug('Adding %s to %s', key, redis_bank_keys) redis_pipe.execute() except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot set the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
[ "def", "store", "(", "bank", ",", "key", ",", "data", ")", ":", "redis_server", "=", "_get_redis_server", "(", ")", "redis_pipe", "=", "redis_server", ".", "pipeline", "(", ")", "redis_key", "=", "_get_key_redis_key", "(", "bank", ",", "key", ")", "redis_b...
Store the data in a Redis key.
[ "Store", "the", "data", "in", "a", "Redis", "key", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L337-L357
train
saltstack/salt
salt/cache/redis_cache.py
fetch
def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value)
python
def fetch(bank, key): ''' Fetch data from the Redis cache. ''' redis_server = _get_redis_server() redis_key = _get_key_redis_key(bank, key) redis_value = None try: redis_value = redis_server.get(redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot fetch the Redis cache key {rkey}: {rerr}'.format(rkey=redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if redis_value is None: return {} return __context__['serial'].loads(redis_value)
[ "def", "fetch", "(", "bank", ",", "key", ")", ":", "redis_server", "=", "_get_redis_server", "(", ")", "redis_key", "=", "_get_key_redis_key", "(", "bank", ",", "key", ")", "redis_value", "=", "None", "try", ":", "redis_value", "=", "redis_server", ".", "g...
Fetch data from the Redis cache.
[ "Fetch", "data", "from", "the", "Redis", "cache", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L360-L376
train
saltstack/salt
salt/cache/redis_cache.py
flush
def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True
python
def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance. ''' redis_server = _get_redis_server() redis_pipe = redis_server.pipeline() if key is None: # will remove all bank keys bank_paths_to_remove = _get_banks_to_remove(redis_server, bank) # tree traversal to get all bank hierarchy for bank_to_remove in bank_paths_to_remove: bank_keys_redis_key = _get_bank_keys_redis_key(bank_to_remove) # Redis key of the SET that stores the bank keys redis_pipe.smembers(bank_keys_redis_key) # fetch these keys log.debug( 'Fetching the keys of the %s bank (%s)', bank_to_remove, bank_keys_redis_key ) try: log.debug('Executing the pipe...') subtree_keys = redis_pipe.execute() # here are the keys under these banks to be removed # this retunrs a list of sets, e.g.: # [set([]), set(['my-key']), set(['my-other-key', 'yet-another-key'])] # one set corresponding to a bank except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the keys under these cache banks: {rbanks}: {rerr}'.format( rbanks=', '.join(bank_paths_to_remove), rerr=rerr ) log.error(mesg) raise SaltCacheError(mesg) total_banks = len(bank_paths_to_remove) # bank_paths_to_remove and subtree_keys have the same length (see above) for index in range(total_banks): bank_keys = subtree_keys[index] # all the keys under this bank bank_path = bank_paths_to_remove[index] for key in bank_keys: redis_key = _get_key_redis_key(bank_path, key) redis_pipe.delete(redis_key) # kill 'em all! log.debug( 'Removing the key %s under the %s bank (%s)', key, bank_path, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank_path) redis_pipe.delete(bank_keys_redis_key) log.debug( 'Removing the bank-keys key for the %s bank (%s)', bank_path, bank_keys_redis_key ) # delete the Redis key where are stored # the list of keys under this bank bank_key = _get_bank_redis_key(bank_path) redis_pipe.delete(bank_key) log.debug('Removing the %s bank (%s)', bank_path, bank_key) # delete the bank key itself else: redis_key = _get_key_redis_key(bank, key) redis_pipe.delete(redis_key) # delete the key cached log.debug( 'Removing the key %s under the %s bank (%s)', key, bank, redis_key ) bank_keys_redis_key = _get_bank_keys_redis_key(bank) redis_pipe.srem(bank_keys_redis_key, key) log.debug( 'De-referencing the key %s from the bank-keys of the %s bank (%s)', key, bank, bank_keys_redis_key ) # but also its reference from $BANKEYS list try: redis_pipe.execute() # Fluuuush except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot flush the Redis cache bank {rbank}: {rerr}'.format(rbank=bank, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) return True
[ "def", "flush", "(", "bank", ",", "key", "=", "None", ")", ":", "redis_server", "=", "_get_redis_server", "(", ")", "redis_pipe", "=", "redis_server", ".", "pipeline", "(", ")", "if", "key", "is", "None", ":", "# will remove all bank keys", "bank_paths_to_remo...
Remove the key from the cache bank with all the key content. If no key is specified, remove the entire bank with all keys and sub-banks inside. This function is using the Redis pipelining for best performance. However, when removing a whole bank, in order to re-create the tree, there are a couple of requests made. In total: - one for node in the hierarchy sub-tree, starting from the bank node - one pipelined request to get the keys under all banks in the sub-tree - one pipeline request to remove the corresponding keys This is not quite optimal, as if we need to flush a bank having a very long list of sub-banks, the number of requests to build the sub-tree may grow quite big. An improvement for this would be loading a custom Lua script in the Redis instance of the user (using the ``register_script`` feature) and call it whenever we flush. This script would only need to build this sub-tree causing problems. It can be added later and the behaviour should not change as the user needs to explicitly allow Salt inject scripts in their Redis instance.
[ "Remove", "the", "key", "from", "the", "cache", "bank", "with", "all", "the", "key", "content", ".", "If", "no", "key", "is", "specified", "remove", "the", "entire", "bank", "with", "all", "keys", "and", "sub", "-", "banks", "inside", ".", "This", "fun...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L379-L471
train
saltstack/salt
salt/cache/redis_cache.py
list_
def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks)
python
def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg) if not banks: return [] return list(banks)
[ "def", "list_", "(", "bank", ")", ":", "redis_server", "=", "_get_redis_server", "(", ")", "bank_redis_key", "=", "_get_bank_redis_key", "(", "bank", ")", "try", ":", "banks", "=", "redis_server", ".", "smembers", "(", "bank_redis_key", ")", "except", "(", "...
Lists entries stored in the specified bank.
[ "Lists", "entries", "stored", "in", "the", "specified", "bank", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L474-L489
train
saltstack/salt
salt/cache/redis_cache.py
contains
def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
python
def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: return redis_server.sismember(bank_redis_key, key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot retrieve the Redis cache key {rkey}: {rerr}'.format(rkey=bank_redis_key, rerr=rerr) log.error(mesg) raise SaltCacheError(mesg)
[ "def", "contains", "(", "bank", ",", "key", ")", ":", "redis_server", "=", "_get_redis_server", "(", ")", "bank_redis_key", "=", "_get_bank_redis_key", "(", "bank", ")", "try", ":", "return", "redis_server", ".", "sismember", "(", "bank_redis_key", ",", "key",...
Checks if the specified bank contains the specified key.
[ "Checks", "if", "the", "specified", "bank", "contains", "the", "specified", "key", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/redis_cache.py#L492-L504
train
saltstack/salt
salt/modules/boto_vpc.py
check_vpc
def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id
python
def check_vpc(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile ''' if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_id or vpc_name ' 'must be provided.') if vpc_name: vpc_id = _get_id(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) elif not _find_vpcs(vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile): log.info('VPC %s does not exist.', vpc_id) return None return vpc_id
[ "def", "check_vpc", "(", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "_exactly_one", "(", "(", "vpc_name", ...
Check whether a VPC with the given name or id exists. Returns the vpc_id or None. Raises SaltInvocationError if both vpc_id and vpc_name are None. Optionally raise a CommandExecutionError if the VPC does not exist. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.check_vpc vpc_name=myvpc profile=awsprofile
[ "Check", "whether", "a", "VPC", "with", "the", "given", "name", "or", "id", "exists", ".", "Returns", "the", "vpc_id", "or", "None", ".", "Raises", "SaltInvocationError", "if", "both", "vpc_id", "and", "vpc_name", "are", "None", ".", "Optionally", "raise", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L201-L228
train
saltstack/salt
salt/modules/boto_vpc.py
_create_resource
def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
python
def _create_resource(resource, name=None, tags=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Create a VPC resource. Returns the resource id if created, or False if not created. ''' try: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) create_resource = getattr(conn, 'create_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('create_' + resource)) if name and _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'A {0} named {1} already exists.'.format( resource, name)}} r = create_resource(**kwargs) if r: if isinstance(r, bool): return {'created': True} else: log.info('A %s with id %s was created', resource, r.id) _maybe_set_name_tag(name, r) _maybe_set_tags(tags, r) if name: _cache_id(name, sub_resource=resource, resource_id=r.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': r.id} else: if name: e = '{0} {1} was not created.'.format(resource, name) else: e = '{0} was not created.'.format(resource) log.warning(e) return {'created': False, 'error': {'message': e}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "_create_resource", "(", "resource", ",", "name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ...
Create a VPC resource. Returns the resource id if created, or False if not created.
[ "Create", "a", "VPC", "resource", ".", "Returns", "the", "resource", "id", "if", "created", "or", "False", "if", "not", "created", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L231-L278
train
saltstack/salt
salt/modules/boto_vpc.py
_delete_resource
def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
python
def _delete_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Delete a VPC resource. Returns True if successful, otherwise False. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: delete_resource = getattr(conn, 'delete_' + resource) except AttributeError: raise AttributeError('{0} function does not exist for boto VPC ' 'connection.'.format('delete_' + resource)) if name: resource_id = _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile) if not resource_id: return {'deleted': False, 'error': {'message': '{0} {1} does not exist.'.format(resource, name)}} if delete_resource(resource_id, **kwargs): _cache_id(name, sub_resource=resource, resource_id=resource_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: if name: e = '{0} {1} was not deleted.'.format(resource, name) else: e = '{0} was not deleted.'.format(resource) return {'deleted': False, 'error': {'message': e}} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "_delete_resource", "(", "resource", ",", "name", "=", "None", ",", "resource_id", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "...
Delete a VPC resource. Returns True if successful, otherwise False.
[ "Delete", "a", "VPC", "resource", ".", "Returns", "True", "if", "successful", "otherwise", "False", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L281-L322
train
saltstack/salt
salt/modules/boto_vpc.py
_get_resource
def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None
python
def _get_resource(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get a VPC resource based on resource type and name or id. Cache the id if name was provided. ''' if not _exactly_one((name, resource_id)): raise SaltInvocationError('One (but not both) of name or id must be ' 'provided.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise if r: if len(r) == 1: if name: _cache_id(name, sub_resource=resource, resource_id=r[0].id, region=region, key=key, keyid=keyid, profile=profile) return r[0] else: raise CommandExecutionError('Found more than one ' '{0} named "{1}"'.format( resource, name)) else: return None
[ "def", "_get_resource", "(", "resource", ",", "name", "=", "None", ",", "resource_id", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "_exactly_one", "(...
Get a VPC resource based on resource type and name or id. Cache the id if name was provided.
[ "Get", "a", "VPC", "resource", "based", "on", "resource", "type", "and", "name", "or", "id", ".", "Cache", "the", "id", "if", "name", "was", "provided", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L325-L370
train
saltstack/salt
salt/modules/boto_vpc.py
_find_resources
def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r
python
def _find_resources(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Get VPC resources based on resource type and name, id, or tags. ''' if all((resource_id, name)): raise SaltInvocationError('Only one of name or id may be ' 'provided.') if not any((resource_id, name, tags)): raise SaltInvocationError('At least one of the following must be ' 'provided: id, name, or tags.') conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) f = 'get_all_{0}'.format(resource) if not f.endswith('s'): f = f + 's' get_resources = getattr(conn, f) filter_parameters = {} if name: filter_parameters['filters'] = {'tag:Name': name} if resource_id: filter_parameters['{0}_ids'.format(resource)] = resource_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value try: r = get_resources(**filter_parameters) except BotoServerError as e: if e.code.endswith('.NotFound'): return None raise return r
[ "def", "_find_resources", "(", "resource", ",", "name", "=", "None", ",", "resource_id", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "...
Get VPC resources based on resource type and name, id, or tags.
[ "Get", "VPC", "resources", "based", "on", "resource", "type", "and", "name", "id", "or", "tags", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L373-L409
train
saltstack/salt
salt/modules/boto_vpc.py
_get_resource_id
def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id
python
def _get_resource_id(resource, name, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. ''' _id = _cache_id(name, sub_resource=resource, region=region, key=key, keyid=keyid, profile=profile) if _id: return _id r = _get_resource(resource, name=name, region=region, key=key, keyid=keyid, profile=profile) if r: return r.id
[ "def", "_get_resource_id", "(", "resource", ",", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "_id", "=", "_cache_id", "(", "name", ",", "sub_resource", "=", "resource", ...
Get an AWS id for a VPC resource by type and name.
[ "Get", "an", "AWS", "id", "for", "a", "VPC", "resource", "by", "type", "and", "name", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L412-L428
train
saltstack/salt
salt/modules/boto_vpc.py
get_resource_id
def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
python
def get_resource_id(resource, name=None, resource_id=None, region=None, key=None, keyid=None, profile=None): ''' Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw ''' try: return {'id': _get_resource_id(resource, name, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
[ "def", "get_resource_id", "(", "resource", ",", "name", "=", "None", ",", "resource_id", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "return", "{", ...
Get an AWS id for a VPC resource by type and name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.get_resource_id internet_gateway myigw
[ "Get", "an", "AWS", "id", "for", "a", "VPC", "resource", "by", "type", "and", "name", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L431-L450
train
saltstack/salt
salt/modules/boto_vpc.py
resource_exists
def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
python
def resource_exists(resource, name=None, resource_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw ''' try: return {'exists': bool(_find_resources(resource, name=name, resource_id=resource_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile))} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
[ "def", "resource_exists", "(", "resource", ",", "name", "=", "None", ",", "resource_id", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "...
Given a resource type and name, return {exists: true} if it exists, {exists: false} if it does not exist, or {error: {message: error text} on error. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.resource_exists internet_gateway myigw
[ "Given", "a", "resource", "type", "and", "name", "return", "{", "exists", ":", "true", "}", "if", "it", "exists", "{", "exists", ":", "false", "}", "if", "it", "does", "not", "exist", "or", "{", "error", ":", "{", "message", ":", "error", "text", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L453-L477
train
saltstack/salt
salt/modules/boto_vpc.py
_get_id
def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None
python
def _get_id(vpc_name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. ''' if vpc_name and not any((cidr, tags)): vpc_id = _cache_id(vpc_name, region=region, key=key, keyid=keyid, profile=profile) if vpc_id: return vpc_id vpc_ids = _find_vpcs(vpc_name=vpc_name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if vpc_ids: log.debug("Matching VPC: %s", " ".join(vpc_ids)) if len(vpc_ids) == 1: vpc_id = vpc_ids[0] if vpc_name: _cache_id(vpc_name, vpc_id, region=region, key=key, keyid=keyid, profile=profile) return vpc_id else: raise CommandExecutionError('Found more than one VPC matching the criteria.') else: log.info('No VPC found.') return None
[ "def", "_get_id", "(", "vpc_name", "=", "None", ",", "cidr", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "vpc_name", "and", "n...
Given VPC properties, return the VPC id if a match is found.
[ "Given", "VPC", "properties", "return", "the", "VPC", "id", "if", "a", "match", "is", "found", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L521-L549
train
saltstack/salt
salt/modules/boto_vpc.py
get_id
def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
python
def get_id(name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc ''' try: return {'id': _get_id(vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile)} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
[ "def", "get_id", "(", "name", "=", "None", ",", "cidr", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "return", "{", "'i...
Given VPC properties, return the VPC id if a match is found. CLI Example: .. code-block:: bash salt myminion boto_vpc.get_id myvpc
[ "Given", "VPC", "properties", "return", "the", "VPC", "id", "if", "a", "match", "is", "found", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L552-L569
train
saltstack/salt
salt/modules/boto_vpc.py
exists
def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)}
python
def exists(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc ''' try: vpc_ids = _find_vpcs(vpc_id=vpc_id, vpc_name=name, cidr=cidr, tags=tags, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} return {'exists': bool(vpc_ids)}
[ "def", "exists", "(", "vpc_id", "=", "None", ",", "name", "=", "None", ",", "cidr", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "t...
Given a VPC ID, check to see if the given VPC ID exists. Returns True if the given VPC ID exists and returns False if the given VPC ID does not exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.exists myvpc
[ "Given", "a", "VPC", "ID", "check", "to", "see", "if", "the", "given", "VPC", "ID", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L572-L598
train
saltstack/salt
salt/modules/boto_vpc.py
create
def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
python
def create(cidr_block, instance_tenancy=None, vpc_name=None, enable_dns_support=None, enable_dns_hostnames=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc = conn.create_vpc(cidr_block, instance_tenancy=instance_tenancy) if vpc: log.info('The newly created VPC id is %s', vpc.id) _maybe_set_name_tag(vpc_name, vpc) _maybe_set_tags(tags, vpc) _maybe_set_dns(conn, vpc.id, enable_dns_support, enable_dns_hostnames) _maybe_name_route_table(conn, vpc.id, vpc_name) if vpc_name: _cache_id(vpc_name, vpc.id, region=region, key=key, keyid=keyid, profile=profile) return {'created': True, 'id': vpc.id} else: log.warning('VPC was not created') return {'created': False} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "create", "(", "cidr_block", ",", "instance_tenancy", "=", "None", ",", "vpc_name", "=", "None", ",", "enable_dns_support", "=", "None", ",", "enable_dns_hostnames", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=",...
Given a valid CIDR block, create a VPC. An optional instance_tenancy argument can be provided. If provided, the valid values are 'default' or 'dedicated' An optional vpc_name argument can be provided. Returns {created: true} if the VPC was created and returns {created: False} if the VPC was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create '10.0.0.0/24'
[ "Given", "a", "valid", "CIDR", "block", "create", "a", "VPC", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L601-L642
train
saltstack/salt
salt/modules/boto_vpc.py
delete
def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
python
def delete(vpc_id=None, name=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc' ''' if name: log.warning('boto_vpc.delete: name parameter is deprecated ' 'use vpc_name instead.') vpc_name = name if not _exactly_one((vpc_name, vpc_id)): raise SaltInvocationError('One (but not both) of vpc_name or vpc_id must be ' 'provided.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: vpc_id = _get_id(vpc_name=vpc_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return {'deleted': False, 'error': {'message': 'VPC {0} not found'.format(vpc_name)}} if conn.delete_vpc(vpc_id): log.info('VPC %s was deleted.', vpc_id) if vpc_name: _cache_id(vpc_name, resource_id=vpc_id, invalidate=True, region=region, key=key, keyid=keyid, profile=profile) return {'deleted': True} else: log.warning('VPC %s was not deleted.', vpc_id) return {'deleted': False} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "delete", "(", "vpc_id", "=", "None", ",", "name", "=", "None", ",", "vpc_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", ...
Given a VPC ID or VPC name, delete the VPC. Returns {deleted: true} if the VPC was deleted and returns {deleted: false} if the VPC was not deleted. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete vpc_id='vpc-6b1fe402' salt myminion boto_vpc.delete name='myvpc'
[ "Given", "a", "VPC", "ID", "or", "VPC", "name", "delete", "the", "VPC", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L645-L692
train
saltstack/salt
salt/modules/boto_vpc.py
describe
def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None}
python
def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc ''' if not any((vpc_id, vpc_name)): raise SaltInvocationError('A valid vpc id or name needs to be specified.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound': # VPC was not found: handle the error and return None. return {'vpc': None} return {'error': boto_err} if not vpc_id: return {'vpc': None} filter_parameters = {'vpc_ids': vpc_id} try: vpcs = conn.get_all_vpcs(**filter_parameters) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} if vpcs: vpc = vpcs[0] # Found! log.debug('Found VPC: %s', vpc.id) keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) return {'vpc': _r} else: return {'vpc': None}
[ "def", "describe", "(", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "any", "(", "(", "vpc_id", ",", "vpc_...
Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc
[ "Given", "a", "VPC", "ID", "describe", "its", "properties", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L695-L747
train
saltstack/salt
salt/modules/boto_vpc.py
describe_vpcs
def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
python
def describe_vpcs(vpc_id=None, name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs ''' keys = ('id', 'cidr_block', 'is_default', 'state', 'tags', 'dhcp_options_id', 'instance_tenancy') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['vpc_ids'] = [vpc_id] if cidr: filter_parameters['filters']['cidr'] = cidr if name: filter_parameters['filters']['tag:Name'] = name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) if vpcs: ret = [] for vpc in vpcs: _r = dict([(k, getattr(vpc, k)) for k in keys]) _r.update({'region': getattr(vpc, 'region').name}) ret.append(_r) return {'vpcs': ret} else: return {'vpcs': []} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
[ "def", "describe_vpcs", "(", "vpc_id", "=", "None", ",", "name", "=", "None", ",", "cidr", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":...
Describe all VPCs, matching the filter criteria if provided. Returns a list of dictionaries with interesting properties. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpcs
[ "Describe", "all", "VPCs", "matching", "the", "filter", "criteria", "if", "provided", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L750-L805
train
saltstack/salt
salt/modules/boto_vpc.py
_find_subnets
def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False
python
def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): ''' Given subnet properties, find and return matching subnet ids ''' if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False
[ "def", "_find_subnets", "(", "subnet_name", "=", "None", ",", "vpc_id", "=", "None", ",", "cidr", "=", "None", ",", "tags", "=", "None", ",", "conn", "=", "None", ")", ":", "if", "not", "any", "(", "[", "subnet_name", ",", "tags", ",", "cidr", "]",...
Given subnet properties, find and return matching subnet ids
[ "Given", "subnet", "properties", "find", "and", "return", "matching", "subnet", "ids" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L808-L839
train
saltstack/salt
salt/modules/boto_vpc.py
create_subnet
def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict
python
def create_subnet(vpc_id=None, cidr_block=None, vpc_name=None, availability_zone=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None, auto_assign_public_ipv4=False): ''' Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} subnet_object_dict = _create_resource('subnet', name=subnet_name, tags=tags, vpc_id=vpc_id, availability_zone=availability_zone, cidr_block=cidr_block, region=region, key=key, keyid=keyid, profile=profile) # if auto_assign_public_ipv4 is requested set that to true using boto3 if auto_assign_public_ipv4: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) conn3.modify_subnet_attribute(MapPublicIpOnLaunch={'Value': True}, SubnetId=subnet_object_dict['id']) return subnet_object_dict
[ "def", "create_subnet", "(", "vpc_id", "=", "None", ",", "cidr_block", "=", "None", ",", "vpc_name", "=", "None", ",", "availability_zone", "=", "None", ",", "subnet_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", ...
Given a valid VPC ID or Name and a CIDR block, create a subnet for the VPC. An optional availability zone argument can be provided. Returns True if the VPC subnet was created and returns False if the VPC subnet was not created. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_subnet vpc_id='vpc-6b1fe402' \\ subnet_name='mysubnet' cidr_block='10.0.0.0/25' salt myminion boto_vpc.create_subnet vpc_name='myvpc' \\ subnet_name='mysubnet', cidr_block='10.0.0.0/25'
[ "Given", "a", "valid", "VPC", "ID", "or", "Name", "and", "a", "CIDR", "block", "create", "a", "subnet", "for", "the", "VPC", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L842-L880
train
saltstack/salt
salt/modules/boto_vpc.py
delete_subnet
def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile)
python
def delete_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403' ''' return _delete_resource(resource='subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "delete_subnet", "(", "subnet_id", "=", "None", ",", "subnet_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "_delete_resource", "(", "resource", ...
Given a subnet ID or name, delete the subnet. Returns True if the subnet was deleted and returns False if the subnet was not deleted. .. versionchanged:: 2015.8.0 Added subnet_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_subnet 'subnet-6a1fe403'
[ "Given", "a", "subnet", "ID", "or", "name", "delete", "the", "subnet", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L883-L903
train
saltstack/salt
salt/modules/boto_vpc.py
subnet_exists
def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False}
python
def subnet_exists(subnet_id=None, name=None, subnet_name=None, cidr=None, tags=None, zones=None, region=None, key=None, keyid=None, profile=None): ''' Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403' ''' if name: log.warning('boto_vpc.subnet_exists: name parameter is deprecated ' 'use subnet_name instead.') subnet_name = name if not any((subnet_id, subnet_name, cidr, tags, zones)): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet id, cidr, subnet_name, ' 'tags, or zones.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as err: return {'error': __utils__['boto.get_error'](err)} filter_parameters = {'filters': {}} if subnet_id: filter_parameters['subnet_ids'] = [subnet_id] if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if cidr: filter_parameters['filters']['cidr'] = cidr if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value if zones: filter_parameters['filters']['availability_zone'] = zones try: subnets = conn.get_all_subnets(**filter_parameters) except BotoServerError as err: boto_err = __utils__['boto.get_error'](err) if boto_err.get('aws', {}).get('code') == 'InvalidSubnetID.NotFound': # Subnet was not found: handle the error and return False. return {'exists': False} return {'error': boto_err} log.debug('The filters criteria %s matched the following subnets:%s', filter_parameters, subnets) if subnets: log.info('Subnet %s exists.', subnet_name or subnet_id) return {'exists': True} else: log.info('Subnet %s does not exist.', subnet_name or subnet_id) return {'exists': False}
[ "def", "subnet_exists", "(", "subnet_id", "=", "None", ",", "name", "=", "None", ",", "subnet_name", "=", "None", ",", "cidr", "=", "None", ",", "tags", "=", "None", ",", "zones", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",...
Check if a subnet exists. Returns True if the subnet exists, otherwise returns False. .. versionchanged:: 2015.8.0 Added subnet_name argument Deprecated name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.subnet_exists subnet_id='subnet-6a1fe403'
[ "Check", "if", "a", "subnet", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L906-L969
train
saltstack/salt
salt/modules/boto_vpc.py
get_subnet_association
def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)}
python
def get_subnet_association(subnets, region=None, key=None, keyid=None, profile=None): ''' Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b'] ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # subnet_ids=subnets can accept either a string or a list subnets = conn.get_all_subnets(subnet_ids=subnets) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} # using a set to store vpc_ids - the use of set prevents duplicate # vpc_id values vpc_ids = set() for subnet in subnets: log.debug('examining subnet id: %s for vpc_id', subnet.id) if subnet in subnets: log.debug('subnet id: %s is associated with vpc id: %s', subnet.id, subnet.vpc_id) vpc_ids.add(subnet.vpc_id) if not vpc_ids: return {'vpc_id': None} elif len(vpc_ids) == 1: return {'vpc_id': vpc_ids.pop()} else: return {'vpc_ids': list(vpc_ids)}
[ "def", "get_subnet_association", "(", "subnets", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=...
Given a subnet (aka: a vpc zone identifier) or list of subnets, returns vpc association. Returns a VPC ID if the given subnets are associated with the same VPC ID. Returns False on an error or if the given subnets are associated with different VPC IDs. CLI Examples: .. code-block:: bash salt myminion boto_vpc.get_subnet_association subnet-61b47516 .. code-block:: bash salt myminion boto_vpc.get_subnet_association ['subnet-61b47516','subnet-2cb9785b']
[ "Given", "a", "subnet", "(", "aka", ":", "a", "vpc", "zone", "identifier", ")", "or", "list", "of", "subnets", "returns", "vpc", "association", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L972-L1015
train
saltstack/salt
salt/modules/boto_vpc.py
describe_subnet
def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret
python
def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet ''' try: subnet = _get_resource('subnet', name=subnet_name, resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not subnet: return {'subnet': None} log.debug('Found subnet: %s', subnet.id) keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') ret = {'subnet': dict((k, getattr(subnet, k)) for k in keys)} explicit_route_table_assoc = _get_subnet_explicit_route_table(ret['subnet']['id'], ret['subnet']['vpc_id'], conn=None, region=region, key=key, keyid=keyid, profile=profile) if explicit_route_table_assoc: ret['subnet']['explicit_route_table_association_id'] = explicit_route_table_assoc return ret
[ "def", "describe_subnet", "(", "subnet_id", "=", "None", ",", "subnet_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "subnet", "=", "_get_resource",...
Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubnet
[ "Given", "a", "subnet", "id", "or", "name", "describe", "its", "properties", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1018-L1053
train
saltstack/salt
salt/modules/boto_vpc.py
describe_subnets
def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
python
def describe_subnets(subnet_ids=None, subnet_names=None, vpc_id=None, cidr=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21 ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if vpc_id: filter_parameters['filters']['vpcId'] = vpc_id if cidr: filter_parameters['filters']['cidrBlock'] = cidr if subnet_names: filter_parameters['filters']['tag:Name'] = subnet_names subnets = conn.get_all_subnets(subnet_ids=subnet_ids, **filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if not subnets: return {'subnets': None} subnets_list = [] keys = ('id', 'cidr_block', 'availability_zone', 'tags', 'vpc_id') for item in subnets: subnet = {} for key in keys: if hasattr(item, key): subnet[key] = getattr(item, key) explicit_route_table_assoc = _get_subnet_explicit_route_table(subnet['id'], subnet['vpc_id'], conn=conn) if explicit_route_table_assoc: subnet['explicit_route_table_association_id'] = explicit_route_table_assoc subnets_list.append(subnet) return {'subnets': subnets_list} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
[ "def", "describe_subnets", "(", "subnet_ids", "=", "None", ",", "subnet_names", "=", "None", ",", "vpc_id", "=", "None", ",", "cidr", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "N...
Given a VPC ID or subnet CIDR, returns a list of associated subnets and their details. Return all subnets if VPC ID or CIDR are not provided. If a subnet id or CIDR is provided, only its associated subnet details will be returned. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnets .. code-block:: bash salt myminion boto_vpc.describe_subnets subnet_ids=['subnet-ba1987ab', 'subnet-ba1987cd'] .. code-block:: bash salt myminion boto_vpc.describe_subnets vpc_id=vpc-123456 .. code-block:: bash salt myminion boto_vpc.describe_subnets cidr=10.0.0.0/21
[ "Given", "a", "VPC", "ID", "or", "subnet", "CIDR", "returns", "a", "list", "of", "associated", "subnets", "and", "their", "details", ".", "Return", "all", "subnets", "if", "VPC", "ID", "or", "CIDR", "are", "not", "provided", ".", "If", "a", "subnet", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1056-L1120
train
saltstack/salt
salt/modules/boto_vpc.py
create_internet_gateway
def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
python
def create_internet_gateway(internet_gateway_name=None, vpc_id=None, vpc_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('internet_gateway', name=internet_gateway_name, tags=tags, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.attach_internet_gateway(r['id'], vpc_id) log.info( 'Attached internet gateway %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "create_internet_gateway", "(", "internet_gateway_name", "=", "None", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile...
Create an Internet Gateway, optionally attaching it to an existing VPC. Returns the internet gateway id if the internet gateway was created and returns False if the internet gateways was not created. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_internet_gateway \\ internet_gateway_name=myigw vpc_name=myvpc
[ "Create", "an", "Internet", "Gateway", "optionally", "attaching", "it", "to", "an", "existing", "VPC", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1123-L1162
train
saltstack/salt
salt/modules/boto_vpc.py
delete_internet_gateway
def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
python
def delete_internet_gateway(internet_gateway_id=None, internet_gateway_name=None, detach=False, region=None, key=None, keyid=None, profile=None): ''' Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw ''' try: if internet_gateway_name: internet_gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not internet_gateway_id: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_name)}} if detach: igw = _get_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) if not igw: return {'deleted': False, 'error': { 'message': 'internet gateway {0} does not exist.'.format( internet_gateway_id)}} if igw.attachments: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.detach_internet_gateway(internet_gateway_id, igw.attachments[0].vpc_id) return _delete_resource('internet_gateway', resource_id=internet_gateway_id, region=region, key=key, keyid=keyid, profile=profile) except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "delete_internet_gateway", "(", "internet_gateway_id", "=", "None", ",", "internet_gateway_name", "=", "None", ",", "detach", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ...
Delete an internet gateway (by name or id). Returns True if the internet gateway was deleted and otherwise False. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_internet_gateway internet_gateway_id=igw-1a2b3c salt myminion boto_vpc.delete_internet_gateway internet_gateway_name=myigw
[ "Delete", "an", "internet", "gateway", "(", "by", "name", "or", "id", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1165-L1216
train
saltstack/salt
salt/modules/boto_vpc.py
_find_nat_gateways
def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False
python
def _find_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Given gateway properties, find and return matching nat gateways ''' if not any((nat_gateway_id, subnet_id, subnet_name, vpc_id, vpc_name)): raise SaltInvocationError('At least one of the following must be ' 'provided: nat_gateway_id, subnet_id, ' 'subnet_name, vpc_id, or vpc_name.') filter_parameters = {'Filter': []} if nat_gateway_id: filter_parameters['NatGatewayIds'] = [nat_gateway_id] if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return False if subnet_id: filter_parameters['Filter'].append({'Name': 'subnet-id', 'Values': [subnet_id]}) if vpc_name: vpc_id = _get_resource_id('vpc', vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: return False if vpc_id: filter_parameters['Filter'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) nat_gateways = [] for ret in __utils__['boto3.paged_call'](conn3.describe_nat_gateways, marker_flag='NextToken', marker_arg='NextToken', **filter_parameters): for gw in ret.get('NatGateways', []): if gw.get('State') in states: nat_gateways.append(gw) log.debug('The filters criteria %s matched the following nat gateways: %s', filter_parameters, nat_gateways) if nat_gateways: return nat_gateways else: return False
[ "def", "_find_nat_gateways", "(", "nat_gateway_id", "=", "None", ",", "subnet_id", "=", "None", ",", "subnet_name", "=", "None", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "states", "=", "(", "'pending'", ",", "'available'", ")", ",", ...
Given gateway properties, find and return matching nat gateways
[ "Given", "gateway", "properties", "find", "and", "return", "matching", "nat", "gateways" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1219-L1269
train
saltstack/salt
salt/modules/boto_vpc.py
nat_gateway_exists
def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile))
python
def nat_gateway_exists(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d' ''' return bool(_find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile))
[ "def", "nat_gateway_exists", "(", "nat_gateway_id", "=", "None", ",", "subnet_id", "=", "None", ",", "subnet_name", "=", "None", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "states", "=", "(", "'pending'", ",", "'available'", ")", ",", ...
Checks if a nat gateway exists. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.nat_gateway_exists nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.nat_gateway_exists subnet_id='subnet-5b05942d'
[ "Checks", "if", "a", "nat", "gateway", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1272-L1299
train
saltstack/salt
salt/modules/boto_vpc.py
describe_nat_gateways
def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)
python
def describe_nat_gateways(nat_gateway_id=None, subnet_id=None, subnet_name=None, vpc_id=None, vpc_name=None, states=('pending', 'available'), region=None, key=None, keyid=None, profile=None): ''' Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d' ''' return _find_nat_gateways(nat_gateway_id=nat_gateway_id, subnet_id=subnet_id, subnet_name=subnet_name, vpc_id=vpc_id, vpc_name=vpc_name, states=states, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "describe_nat_gateways", "(", "nat_gateway_id", "=", "None", ",", "subnet_id", "=", "None", ",", "subnet_name", "=", "None", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "states", "=", "(", "'pending'", ",", "'available'", ")", ","...
Return a description of nat gateways matching the selection criteria This function requires boto3 to be installed. CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_nat_gateways nat_gateway_id='nat-03b02643b43216fe7' salt myminion boto_vpc.describe_nat_gateways subnet_id='subnet-5b05942d'
[ "Return", "a", "description", "of", "nat", "gateways", "matching", "the", "selection", "criteria" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1302-L1327
train
saltstack/salt
salt/modules/boto_vpc.py
create_nat_gateway
def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
python
def create_nat_gateway(subnet_id=None, subnet_name=None, allocation_id=None, region=None, key=None, keyid=None, profile=None): ''' Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet ''' try: if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} else: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if not allocation_id: address = conn3.allocate_address(Domain='vpc') allocation_id = address.get('AllocationId') # Have to go to boto3 to create NAT gateway r = conn3.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id) return {'created': True, 'id': r.get('NatGateway', {}).get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "create_nat_gateway", "(", "subnet_id", "=", "None", ",", "subnet_name", "=", "None", ",", "allocation_id", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try"...
Create a NAT Gateway within an existing subnet. If allocation_id is specified, the elastic IP address it references is associated with the gateway. Otherwise, a new allocation_id is created and used. This function requires boto3 to be installed. Returns the nat gateway id if the nat gateway was created and returns False if the nat gateway was not created. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.create_nat_gateway subnet_name=mysubnet
[ "Create", "a", "NAT", "Gateway", "within", "an", "existing", "subnet", ".", "If", "allocation_id", "is", "specified", "the", "elastic", "IP", "address", "it", "references", "is", "associated", "with", "the", "gateway", ".", "Otherwise", "a", "new", "allocation...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1330-L1380
train
saltstack/salt
salt/modules/boto_vpc.py
delete_nat_gateway
def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
python
def delete_nat_gateway(nat_gateway_id, release_eips=False, region=None, key=None, keyid=None, profile=None, wait_for_delete=False, wait_for_delete_retries=5): ''' Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c ''' try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] conn3.delete_nat_gateway(NatGatewayId=nat_gateway_id) # wait for deleting nat gateway to finish prior to attempt to release elastic ips if wait_for_delete: for retry in range(wait_for_delete_retries, 0, -1): if gwinfo and gwinfo['State'] not in ['deleted', 'failed']: time.sleep((2 ** (wait_for_delete_retries - retry)) + (random.randint(0, 1000) / 1000.0)) gwinfo = conn3.describe_nat_gateways(NatGatewayIds=[nat_gateway_id]) if gwinfo: gwinfo = gwinfo.get('NatGateways', [None])[0] continue break if release_eips and gwinfo: for addr in gwinfo.get('NatGatewayAddresses'): conn3.release_address(AllocationId=addr.get('AllocationId')) return {'deleted': True} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "delete_nat_gateway", "(", "nat_gateway_id", ",", "release_eips", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "wait_for_delete", "=", "False", ",", "wait_for_delete_re...
Delete a nat gateway (by id). Returns True if the internet gateway was deleted and otherwise False. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 nat_gateway_id Id of the NAT Gateway releaes_eips whether to release the elastic IPs associated with the given NAT Gateway Id region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. wait_for_delete whether to wait for delete of the NAT gateway to be in failed or deleted state after issuing the delete call. wait_for_delete_retries NAT gateway may take some time to be go into deleted or failed state. During the deletion process, subsequent release of elastic IPs may fail; this state will automatically retry this number of times to ensure the NAT gateway is in deleted or failed state before proceeding. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_nat_gateway nat_gateway_id=igw-1a2b3c
[ "Delete", "a", "nat", "gateway", "(", "by", "id", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1383-L1456
train
saltstack/salt
salt/modules/boto_vpc.py
create_customer_gateway
def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
python
def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534 ''' return _create_resource('customer_gateway', customer_gateway_name, type=vpn_connection_type, ip_address=ip_address, bgp_asn=bgp_asn, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "create_customer_gateway", "(", "vpn_connection_type", ",", "ip_address", ",", "bgp_asn", ",", "customer_gateway_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profil...
Given a valid VPN connection type, a static IP address and a customer gateway’s Border Gateway Protocol (BGP) Autonomous System Number, create a customer gateway. Returns the customer gateway id if the customer gateway was created and returns False if the customer gateway was not created. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_customer_gateway 'ipsec.1', '12.1.2.3', 65534
[ "Given", "a", "valid", "VPN", "connection", "type", "a", "static", "IP", "address", "and", "a", "customer", "gateway’s", "Border", "Gateway", "Protocol", "(", "BGP", ")", "Autonomous", "System", "Number", "create", "a", "customer", "gateway", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1459-L1482
train
saltstack/salt
salt/modules/boto_vpc.py
delete_customer_gateway
def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile)
python
def delete_customer_gateway(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df' ''' return _delete_resource(resource='customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "delete_customer_gateway", "(", "customer_gateway_id", "=", "None", ",", "customer_gateway_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "_delete_re...
Given a customer gateway ID or name, delete the customer gateway. Returns True if the customer gateway was deleted and returns False if the customer gateway was not deleted. .. versionchanged:: 2015.8.0 Added customer_gateway_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_customer_gateway 'cgw-b6a247df'
[ "Given", "a", "customer", "gateway", "ID", "or", "name", "delete", "the", "customer", "gateway", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1485-L1507
train
saltstack/salt
salt/modules/boto_vpc.py
customer_gateway_exists
def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile)
python
def customer_gateway_exists(customer_gateway_id=None, customer_gateway_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw ''' return resource_exists('customer_gateway', name=customer_gateway_name, resource_id=customer_gateway_id, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "customer_gateway_exists", "(", "customer_gateway_id", "=", "None", ",", "customer_gateway_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "resource_e...
Given a customer gateway ID, check if the customer gateway ID exists. Returns True if the customer gateway ID exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.customer_gateway_exists cgw-b6a247df salt myminion boto_vpc.customer_gateway_exists customer_gatway_name=mycgw
[ "Given", "a", "customer", "gateway", "ID", "check", "if", "the", "customer", "gateway", "ID", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1510-L1528
train
saltstack/salt
salt/modules/boto_vpc.py
create_dhcp_options
def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
python
def create_dhcp_options(domain_name=None, domain_name_servers=None, ntp_servers=None, netbios_name_servers=None, netbios_node_type=None, dhcp_options_name=None, tags=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc' ''' try: if vpc_id or vpc_name: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} r = _create_resource('dhcp_options', name=dhcp_options_name, domain_name=domain_name, domain_name_servers=domain_name_servers, ntp_servers=ntp_servers, netbios_name_servers=netbios_name_servers, netbios_node_type=netbios_node_type, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and vpc_id: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.associate_dhcp_options(r['id'], vpc_id) log.info( 'Associated options %s to VPC %s', r['id'], vpc_name or vpc_id ) return r except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "create_dhcp_options", "(", "domain_name", "=", "None", ",", "domain_name_servers", "=", "None", ",", "ntp_servers", "=", "None", ",", "netbios_name_servers", "=", "None", ",", "netbios_node_type", "=", "None", ",", "dhcp_options_name", "=", "None", ",", ...
Given valid DHCP options, create a DHCP options record, optionally associating it with an existing VPC. Returns True if the DHCP options record was created and returns False if the DHCP options record was not deleted. .. versionchanged:: 2015.8.0 Added vpc_name and vpc_id arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_dhcp_options domain_name='example.com' \\ domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' \\ netbios_name_servers='[10.0.0.1]' netbios_node_type=1 \\ vpc_name='myvpc'
[ "Given", "valid", "DHCP", "options", "create", "a", "DHCP", "options", "record", "optionally", "associating", "it", "with", "an", "existing", "VPC", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1531-L1577
train
saltstack/salt
salt/modules/boto_vpc.py
get_dhcp_options
def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)}
python
def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0 ''' if not any((dhcp_options_name, dhcp_options_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'dhcp_options_name, dhcp_options_id.') if not dhcp_options_id and dhcp_options_name: dhcp_options_id = _get_resource_id('dhcp_options', dhcp_options_name, region=region, key=key, keyid=keyid, profile=profile) if not dhcp_options_id: return {'dhcp_options': {}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = conn.get_all_dhcp_options(dhcp_options_ids=[dhcp_options_id]) except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)} if not r: return {'dhcp_options': None} keys = ('domain_name', 'domain_name_servers', 'ntp_servers', 'netbios_name_servers', 'netbios_node_type') return {'dhcp_options': dict((k, r[0].options.get(k)) for k in keys)}
[ "def", "get_dhcp_options", "(", "dhcp_options_name", "=", "None", ",", "dhcp_options_id", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "any", "(", "(", ...
Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0
[ "Return", "a", "dict", "with", "the", "current", "values", "of", "the", "requested", "DHCP", "options", "set" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1580-L1616
train
saltstack/salt
salt/modules/boto_vpc.py
delete_dhcp_options
def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile)
python
def delete_dhcp_options(dhcp_options_id=None, dhcp_options_name=None, region=None, key=None, keyid=None, profile=None): ''' Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df' ''' return _delete_resource(resource='dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "delete_dhcp_options", "(", "dhcp_options_id", "=", "None", ",", "dhcp_options_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "_delete_resource", "...
Delete dhcp options by id or name. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_dhcp_options 'dopt-b6a247df'
[ "Delete", "dhcp", "options", "by", "id", "or", "name", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1619-L1638
train
saltstack/salt
salt/modules/boto_vpc.py
associate_dhcp_options_to_vpc
def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)}
python
def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402' ''' try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'associated': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.associate_dhcp_options(dhcp_options_id, vpc_id): log.info('DHCP options with id %s were associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': True} else: log.warning('DHCP options with id %s were not associated with VPC %s', dhcp_options_id, vpc_id) return {'associated': False, 'error': {'message': 'DHCP options could not be associated.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "associate_dhcp_options_to_vpc", "(", "dhcp_options_id", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", ...
Given valid DHCP options id and a valid VPC id, associate the DHCP options record with the VPC. Returns True if the DHCP options record were associated and returns False if the DHCP options record was not associated. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_dhcp_options_to_vpc 'dhcp-a0bl34pp' 'vpc-6b1fe402'
[ "Given", "valid", "DHCP", "options", "id", "and", "a", "valid", "VPC", "id", "associate", "the", "DHCP", "options", "record", "with", "the", "VPC", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1641-L1671
train
saltstack/salt
salt/modules/boto_vpc.py
dhcp_options_exists
def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
python
def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' ''' if name: log.warning('boto_vpc.dhcp_options_exists: name parameter is deprecated ' 'use dhcp_options_name instead.') dhcp_options_name = name return resource_exists('dhcp_options', name=dhcp_options_name, resource_id=dhcp_options_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "dhcp_options_exists", "(", "dhcp_options_id", "=", "None", ",", "name", "=", "None", ",", "dhcp_options_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", ...
Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: bash salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp'
[ "Check", "if", "a", "dhcp", "option", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1674-L1697
train
saltstack/salt
salt/modules/boto_vpc.py
create_network_acl
def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r
python
def create_network_acl(vpc_id=None, vpc_name=None, network_acl_name=None, subnet_id=None, subnet_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402' ''' _id = vpc_name or vpc_id try: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(_id)}} if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} elif subnet_id: if not _get_resource('subnet', resource_id=subnet_id, region=region, key=key, keyid=keyid, profile=profile): return {'created': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_id)}} r = _create_resource('network_acl', name=network_acl_name, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile) if r.get('created') and subnet_id: try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(r['id'], subnet_id) except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} r['association_id'] = association_id return r
[ "def", "create_network_acl", "(", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "network_acl_name", "=", "None", ",", "subnet_id", "=", "None", ",", "subnet_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key",...
Given a vpc_id, creates a network acl. Returns the network acl id if successful, otherwise returns False. .. versionchanged:: 2015.8.0 Added vpc_name, subnet_id, and subnet_name arguments CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl 'vpc-6b1fe402'
[ "Given", "a", "vpc_id", "creates", "a", "network", "acl", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1700-L1757
train
saltstack/salt
salt/modules/boto_vpc.py
delete_network_acl
def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile)
python
def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False, region=None, key=None, keyid=None, profile=None): ''' Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true ''' if disassociate: network_acl = _get_resource('network_acl', name=network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if network_acl and network_acl.associations: subnet_id = network_acl.associations[0].subnet_id try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.disassociate_network_acl(subnet_id) except BotoServerError: pass return _delete_resource(resource='network_acl', name=network_acl_name, resource_id=network_acl_id, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "delete_network_acl", "(", "network_acl_id", "=", "None", ",", "network_acl_name", "=", "None", ",", "disassociate", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":...
Delete a network acl based on the network_acl_id or network_acl_name provided. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\ disassociate=false .. code-block:: bash salt myminion boto_vpc.delete_network_acl network_acl_name='myacl' \\ disassociate=true
[ "Delete", "a", "network", "acl", "based", "on", "the", "network_acl_id", "or", "network_acl_name", "provided", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1760-L1793
train
saltstack/salt
salt/modules/boto_vpc.py
network_acl_exists
def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
python
def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36' ''' if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated ' 'use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "network_acl_exists", "(", "network_acl_id", "=", "None", ",", "name", "=", "None", ",", "network_acl_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "...
Checks if a network acl exists. Returns True if the network acl exists or returns False if it doesn't exist. CLI Example: .. code-block:: bash salt myminion boto_vpc.network_acl_exists network_acl_id='acl-5fb85d36'
[ "Checks", "if", "a", "network", "acl", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1796-L1819
train
saltstack/salt
salt/modules/boto_vpc.py
associate_network_acl_to_subnet
def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)}
python
def associate_network_acl_to_subnet(network_acl_id=None, subnet_id=None, network_acl_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet' ''' if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'associated': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name)}} if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_network_acl(network_acl_id, subnet_id) if association_id: log.info('Network ACL with id %s was associated with subnet %s', network_acl_id, subnet_id) return {'associated': True, 'id': association_id} else: log.warning('Network ACL with id %s was not associated with subnet %s', network_acl_id, subnet_id) return {'associated': False, 'error': {'message': 'ACL could not be assocaited.'}} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "associate_network_acl_to_subnet", "(", "network_acl_id", "=", "None", ",", "subnet_id", "=", "None", ",", "network_acl_name", "=", "None", ",", "subnet_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None"...
Given a network acl and subnet ids or names, associate a network acl to a subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='acl-5fb85d36' subnet_id='subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_network_acl_to_subnet \\ network_acl_id='myacl' subnet_id='mysubnet'
[ "Given", "a", "network", "acl", "and", "subnet", "ids", "or", "names", "associate", "a", "network", "acl", "to", "a", "subnet", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1822-L1870
train
saltstack/salt
salt/modules/boto_vpc.py
disassociate_network_acl
def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)}
python
def disassociate_network_acl(subnet_id=None, vpc_id=None, subnet_name=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403' ''' if not _exactly_one((subnet_name, subnet_id)): raise SaltInvocationError('One (but not both) of subnet_id or subnet_name ' 'must be provided.') if all((vpc_name, vpc_id)): raise SaltInvocationError('Only one of vpc_id or vpc_name ' 'may be provided.') try: if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'disassociated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if vpc_name or vpc_id: vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.disassociate_network_acl(subnet_id, vpc_id=vpc_id) return {'disassociated': True, 'association_id': association_id} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "disassociate_network_acl", "(", "subnet_id", "=", "None", ",", "vpc_id", "=", "None", ",", "subnet_name", "=", "None", ",", "vpc_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", ...
Given a subnet ID, disassociates a network acl. CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_network_acl 'subnet-6a1fe403'
[ "Given", "a", "subnet", "ID", "disassociates", "a", "network", "acl", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1873-L1909
train
saltstack/salt
salt/modules/boto_vpc.py
create_network_acl_entry
def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs)
python
def create_network_acl_entry(network_acl_id=None, rule_number=None, protocol=None, rule_action=None, cidr_block=None, egress=None, network_acl_name=None, icmp_code=None, icmp_type=None, port_range_from=None, port_range_to=None, region=None, key=None, keyid=None, profile=None): ''' Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true ''' kwargs = locals() return _create_network_acl_entry(**kwargs)
[ "def", "create_network_acl_entry", "(", "network_acl_id", "=", "None", ",", "rule_number", "=", "None", ",", "protocol", "=", "None", ",", "rule_action", "=", "None", ",", "cidr_block", "=", "None", ",", "egress", "=", "None", ",", "network_acl_name", "=", "...
Creates a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.create_network_acl_entry 'acl-5fb85d36' '32767' \\ 'all' 'deny' '0.0.0.0/0' egress=true
[ "Creates", "a", "network", "acl", "entry", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L1965-L1983
train
saltstack/salt
salt/modules/boto_vpc.py
delete_network_acl_entry
def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
python
def delete_network_acl_entry(network_acl_id=None, rule_number=None, egress=None, network_acl_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767' ''' if not _exactly_one((network_acl_name, network_acl_id)): raise SaltInvocationError('One (but not both) of network_acl_id or ' 'network_acl_name must be provided.') for v in ('rule_number', 'egress'): if locals()[v] is None: raise SaltInvocationError('{0} is required.'.format(v)) if network_acl_name: network_acl_id = _get_resource_id('network_acl', network_acl_name, region=region, key=key, keyid=keyid, profile=profile) if not network_acl_id: return {'deleted': False, 'error': {'message': 'Network ACL {0} does not exist.'.format(network_acl_name or network_acl_id)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deleted = conn.delete_network_acl_entry(network_acl_id, rule_number, egress=egress) if deleted: log.info('Network ACL entry was deleted') else: log.warning('Network ACL was not deleted') return {'deleted': deleted} except BotoServerError as e: return {'deleted': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "delete_network_acl_entry", "(", "network_acl_id", "=", "None", ",", "rule_number", "=", "None", ",", "egress", "=", "None", ",", "network_acl_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", ...
Deletes a network acl entry. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_network_acl_entry 'acl-5fb85d36' '32767'
[ "Deletes", "a", "network", "acl", "entry", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2008-L2045
train
saltstack/salt
salt/modules/boto_vpc.py
create_route_table
def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile)
python
def create_route_table(vpc_id=None, vpc_name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable' ''' vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile) if not vpc_id: return {'created': False, 'error': {'message': 'VPC {0} does not exist.'.format(vpc_name or vpc_id)}} return _create_resource('route_table', route_table_name, tags=tags, vpc_id=vpc_id, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "create_route_table", "(", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "route_table_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", ...
Creates a route table. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Examples: .. code-block:: bash salt myminion boto_vpc.create_route_table vpc_id='vpc-6b1fe402' \\ route_table_name='myroutetable' salt myminion boto_vpc.create_route_table vpc_name='myvpc' \\ route_table_name='myroutetable'
[ "Creates", "a", "route", "table", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2048-L2071
train
saltstack/salt
salt/modules/boto_vpc.py
delete_route_table
def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile)
python
def delete_route_table(route_table_id=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable' ''' return _delete_resource(resource='route_table', name=route_table_name, resource_id=route_table_id, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "delete_route_table", "(", "route_table_id", "=", "None", ",", "route_table_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "_delete_resource", "(",...
Deletes a route table. CLI Examples: .. code-block:: bash salt myminion boto_vpc.delete_route_table route_table_id='rtb-1f382e7d' salt myminion boto_vpc.delete_route_table route_table_name='myroutetable'
[ "Deletes", "a", "route", "table", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2074-L2089
train